LoveLovelyJava one LoveLovelyJava one - 3 months ago 8
Java Question

string split method is missing the last spliters

I am trying to split a string by the split method:

String s = "2#1###ss###";
String[] array = s.split("#");
for(String s1 : array){
System.out.println("=>"+s1);
}


The result is

=>2
=>1
=>
=>
=>ss


but I think it should be:

=>2
=>1
=>
=>
=>ss
=>
=>
=>

Answer

From the docs for String.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.

You could use the two-argument method with a high limit instead.