Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.
}
like image 814
Tom Joe Avatar asked Oct 12 '25 09:10

Tom Joe


1 Answers

The single element string array entry is in fact empty string. This makes sense, because the split on " " fails, and hence you just get back the input with which you started. As a general approach, you may consider that if splitting returns you a single element, then the split did not match anything, leaving you with the starting input string.

like image 154
Tim Biegeleisen Avatar answered Oct 14 '25 23:10

Tim Biegeleisen