Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String split inconsistency

Tags:

java

string

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?

like image 427
Lahiru Chandima Avatar asked Oct 25 '25 06:10

Lahiru Chandima


1 Answers

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.

like image 194
Eran Avatar answered Oct 26 '25 20:10

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!