passing 0 as a limit argument prevents trailing empty strings, but how does one prevent leading empty strings?
for instance
String[] test = "/Test/Stuff".split("/");
results in an array with "", "Test", "Stuff".
Yeah, I know I could roll my own Tokenizer... but the API docs for StringTokenizer say
"StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split"
The natural consequence is that if the string does not contain the delimiter, a singleton array containing just the input string is returned, Second, remove all the rightmost empty strings. This is the reason ",,,". split(",") returns empty array.
Using the isEmpty() Method The isEmpty() method returns true or false depending on whether or not our string contains any text. It's easily chainable with a string == null check, and can even differentiate between blank and empty strings: String string = "Hello there"; if (string == null || string.
Both String#isEmpty and String#length can be used to check for empty strings. To be precise, String#trim will remove all leading and trailing characters with a Unicode code less than or equal to U+0020. And also, remember that Strings are immutable, so calling trim won't actually change the underlying string.
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", "/");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With