Possible Duplicate:
Java split() method strips empty strings at the end?
In Java, I'm using the String split method to split a string containing values separated by semicolons.
Currently, I have the following line that works in 99% of all cases.
String[] fields = optionsTxt.split(";");
When using following String everything is perfect:
"House;Car;Street;Place" => [House] [Car] [Street] [Place]
But when i use following String, split Method ignores the last two semicolons.
"House;Car;;" => [House][Car]
What's wrong? Or is there any workaround?
Try below:
String[] = data.split(";", -1);
Refer to Javadoc for the split method taking two arguments for details.
When calling String.split(String), it calls String.split(String, 0) and that discards trailing empty strings (as the docs say it), when calling String.split(String, n) with n < 0 it won't discard anything.
You can use guava's Splitter
From documentation:
Splitter.on(',').split("foo,,bar, quux")
Will return iterable of ["foo", "", "bar", " quux"]
This is explicitly mentioned in the Java API javadocs:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)
"Trailing empty strings are therefore not included in the resulting array. "
If you want the empty strings, try using the two-argument version of the same method, with a negative second argument:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String,%20int)
"If n is non-positive then the pattern will be applied as many times as possible and the array can have any length."
Edit: Hm, my links with anchors are not working.
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