Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting an empty string in Java seems to violate documentation by not discarding trailing empty strings

Tags:

java

string

regex

System.out.println(",".split(",", 0).length);
System.out.println("".split(",", 0).length);

prints:

0
1

This seems odd. According to the documentation for String.split(pattern, n),

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.

In the second case, when splitting an empty string, this rule seems to be ignored. Is this expected behavior?

like image 396
Hans Brende Avatar asked May 02 '26 17:05

Hans Brende


1 Answers

As from docs

If the expression does not match any part of the input then the resulting array has just one element, namely this string

"".split(",", 0).length mean it is similar to this

    System.out.println(new String[]{""}.length);

There was no , in the string "" so the array contain single element "" an empty string , result in array length as 1

another example

    System.out.println("aaa".split(",", 0).length); // 1
    System.out.println("aaa".split("," , 0)[0]);    // aaa
like image 185
Pavneet_Singh Avatar answered May 05 '26 05:05

Pavneet_Singh



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!