split method of class String ignores semicolon separators

17,720

Solution 1

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.

Solution 2

You can use guava's Splitter

From documentation:

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

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

Solution 3

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.

Share:
17,720

Related videos on Youtube

endian
Author by

endian

CEO @ instant:solutions Development Operations @ Smartbow GmbH Twitter: @andlinger

Updated on June 04, 2022

Comments

  • endian
    endian almost 2 years

    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?

  • thejh
    thejh over 12 years
    I think the OP doesn't want .trimResults().omitEmptyStrings();...
  • Baked Inhalf
    Baked Inhalf over 6 years
    Yes! String[] = data.split(";"); Could not handle multiple semicolons. Adding -1 solved it!