Lahiru Chandima Lahiru Chandima - 2 months ago 4x
Java Question

Java String split inconsistency

If I split "hello|" and "|hello" with "|" character, then I get one value for the first and two values for the second version.

String[] arr1 = new String("hello|").split("\\|");
String[] arr2 = new String("|hello").split("\\|");
System.out.println("arr1 length: " + arr1.length + "\narr2 length: " + arr2.length);

This prints out:

arr1 length: 1

arr2 length: 2

Why is this?


According to java docs. split creates an empty String if the first character is the separator, but doesn't create an empty String (or empty Strings) if the last character (or consecutive characters) is the separator. You will get the same behavior regardless of the separator you use.