How to prevent java.lang.String.split() from creating a leading empty string?

I think you shall have to manually remove the first empty string. A simple way to do that is this -

  String string, subString;
  int index;
  String[] test;

  string = "/Test/Stuff";
  index  = string.indexOf("/");
  subString = string.substring(index+1);

  test = subString.split("/"); 

This will exclude the leading empty string.


I don't think there is a way you could do this with the built-in split method. So you have two options:

1) Make your own split

2) Iterate through the array after calling split and remove empty elements

If you make your own split you can just combine these two options

public List<String> split(String inString)
{
   List<String> outList = new ArrayList<>();
   String[]     test    = inString.split("/");

   for(String s : test)
   {
       if(s != null && s.length() > 0)
           outList.add(s);
   }

   return outList;
}

or you could just check for the delimiter being in the first position before you call split and ignore the first character if it does:

String   delimiter       = "/";
String   delimitedString = "/Test/Stuff";
String[] test;

if(delimitedString.startsWith(delimiter)){
    //start at the 1st character not the 0th
    test = delimitedString.substring(1).split(delimiter); 
}
else
    test = delimitedString.split(delimiter);

Your best bet is probably just to strip out any leading delimiter:

String input = "/Test/Stuff";
String[] test = input.replaceFirst("^/", "").split("/");

You can make it more generic by putting it in a method:

public String[] mySplit(final String input, final String delim)
{
    return input.replaceFirst("^" + delim, "").split(delim);
}

String[] test = mySplit("/Test/Stuff", "/");

Apache Commons has a utility method for exactly this: org.apache.commons.lang.StringUtils.split

StringUtils.split()

Actually in our company we now prefer using this method for splitting in all our projects.

Tags:

Java

String