Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Split - wrong length

Tags:

java

split

Why am I receiving a length of 3 instead of 4? How can I fix this to give the proper length?

String s="+9851452;;FERRARI;;";
String split[]=s.split("[;]");
System.out.println(split.length);
like image 755
Pablo Avatar asked Mar 13 '15 19:03

Pablo


2 Answers

You're receiving a length of 3 because for split,

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

If you specify a negative limit, it'll work fine:

    String s="+9851452;;FERRARI;;";
    String split[]=s.split(";", -1);
    System.out.println(Arrays.toString(split));

You'll just need to ignore or remove the 5th item, or remove the trailing ; - it shows up because there are 5 (potentially blank) strings on either sides of 4 tokens. See the docs for more info.

like image 77
mk. Avatar answered Nov 11 '22 20:11

mk.


String split[]=s.split("[;]", -1);

like image 20
Thomas D. K. Teixeira Avatar answered Nov 11 '22 20:11

Thomas D. K. Teixeira