Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

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"

like image 455
marathon Avatar asked Feb 22 '12 05:02

marathon


People also ask

What happens if you split an empty string?

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.

How do you make sure a string is not empty?

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.

Can we trim empty string in Java?

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.


1 Answers

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", "/"); 
like image 191
Joe Attardi Avatar answered Oct 02 '22 00:10

Joe Attardi