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

Solution 1:

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", "/");

Solution 2:

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.