Java - Why does string split for empty string give me a non empty array?

Tom Joe :

I want to split a String by a space. When I use an empty string, I expect to get an array of zero strings. Instead, I get an array with only empty string. Why ?

public static void main(String [] args){
    String x = "";
    String [] xs = x.split(" ");
    System.out.println("strings :" + xs.length);//prints 1 instead of 0.
}
kaya3 :

An interesting puzzle indeed:

> "".split(" ")
String[1] { "" }
> " ".split(" ")
String[0] {  }

The question is, when you split the empty string, why does the result contain the empty string, and when you split a space, why does the result not contain anything? It seems inconsistent, but all is explained in the documentation.

The String.split(String) method "works as if by invoking the two-argument split method with the given expression and a limit argument of zero", so let's read the docs for String.split(String, int). The case of the empty string is answered by this part:

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

The empty string has no part matching a space, so the output is an array containing one element, the input string, exactly as the docs say should happen.

The case of the string " " is answered by these two parts:

A zero-width match at the beginning however never produces such empty leading substring.

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.

The whole input string " " matches the splitting pattern. In principle we could include an empty string on either side of the match, but the docs say that an empty leading substring is never included, and (because the limit parameter n = 0) the trailing empty string is also discarded. Hence, the empty strings before and after the match are both not included in the resulting array, so it's empty.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=216115&siteId=1