Hans Brende
Hans Brende

Reputation: 8527

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

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?

Upvotes: 3

Views: 73

Answers (1)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

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

Upvotes: 4

Related Questions