Shedom Wei Shedom Wei - 3 months ago 10
Java Question

what size of the array after Java String.split()?

In Java, when the string text is "a#b#c", the array after split("#") is ["a","b","c"] and the length is 3;

when the text is "a#", the array turns to be ["a"]. Why did i not get a array of ["a", ""]?

what's the trick of it?

Answer

You probably want

s.split("#", -1);

From the docs on the 2-arg form:

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.