I'm writing some simple Java code for handling strings, and I'm trying to understand the behavior of the String.split() method. I've come across this strange edge case behavior. Consider the three following examples.
String string = "";
String[] parts = string.split("-");
In this case, parts
has a single element: the empty string.
String string = "-b";
String[] parts = string.split("-");
In this case, parts
has two elements: the empty string, and the string "b"
.
So far so good. But then:
String string = "-";
String[] parts = string.split("-");
In this case, parts
has zero elements!
My question is:
in the last example, why does the array parts
have zero elements, instead of two elements: two occurrences of the empty string? If it counts the empty string on the left side of the separator -
in the second example, shouldn't it count the empty strings on either side in the third example?