Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split method of class String ignores semicolon separators [duplicate]

Tags:

java

split

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?

like image 812
endian Avatar asked Jan 19 '12 12:01

endian


3 Answers

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.

like image 155
Shadow Avatar answered Nov 15 '22 15:11

Shadow


You can use guava's Splitter

From documentation:

Splitter.on(',').split("foo,,bar, quux")

Will return iterable of ["foo", "", "bar", " quux"]

like image 41
Mairbek Khadikov Avatar answered Nov 15 '22 14:11

Mairbek Khadikov


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.

like image 39
Jolta Avatar answered Nov 15 '22 16:11

Jolta