Reputation: 2781
This is a follow-up to this question.
The question is on the second line below.
"".split("x"); //returns {""} // ok
"x".split("x"); //returns {} but shouldn't it return {""} because it's the string before "x" ?
"xa".split("x"); //returns {"", "a"} // see?, here "" is the first string returned
"ax".split("x"); //returns {"a"}
Upvotes: 8
Views: 1658
Reputation: 14289
To include the trailing empty strings, use the other implementation of split
.
"".split("x", -1); // returns {""} - valid - when no match is found, return the original string
"x".split("x", -1); // returns {"", ""} - valid - trailing empty strings are included in the resultant array {"", ""}
"xa".split("x", -1); // returns {"", "a"} - valid
"ax".split("x", -1); // returns {"a", ""} - valid - trailing empty strings are included in the resultant array {"a", ""}
Upvotes: 0
Reputation: 1180
As per the java.util.regex.Pattern
source, which String.split(..)
uses,
"".split("x"); // returns {""} - valid - when no match is found, return the original string
"x".split("x"); // returns {} - valid - trailing empty strings are removed from the resultant array {"", ""}
"xa".split("x"); // returns {"", "a"} - valid - only trailing empty strings are removed
"ax".split("x"); // returns {"a"} - valid - trailing empty strings are removed from the resultant array {"a", ""}
Upvotes: 5
Reputation: 42047
No, because according to the relevant javadoc "trailing empty strings will be discarded".
Upvotes: 7