14

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?

Community
  • 1
  • 1
endian
  • 4,761
  • 7
  • 32
  • 54

3 Answers3

20

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.

Ryan Lundy
  • 204,559
  • 37
  • 180
  • 211
Shadow
  • 6,161
  • 3
  • 20
  • 14
1

You can use guava's Splitter

From documentation:

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

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

Mairbek Khadikov
  • 7,939
  • 3
  • 35
  • 51
1

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.

Jolta
  • 2,620
  • 1
  • 29
  • 42