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"}
If the delimiter is an empty string, the split() method will return an array of elements, one element for each character of string. If you specify an empty string for string, the split() method will return an empty string and not an array of strings.
Using String. split() Method. The split() method of the String class is used to split a string into an array of String objects based on the specified delimiter that matches the regular expression.
Using split() The following example defines a function that splits a string into an array of strings using separator .
Q #4) How to split a string in Java without delimiter or How to split each character in Java? Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.
No, because according to the relevant javadoc "trailing empty strings will be discarded".
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", ""}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With