Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String split behaviour on empty string and on single delimiter string

Tags:

java

scala

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"}
like image 898
snappy Avatar asked Nov 16 '11 18:11

snappy


People also ask

What happens if you split an empty string?

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.

How do you split a string with a delimiter?

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.

Which string function splits a string based on a delimiter?

Using split() The following example defines a function that splits a string into an array of strings using separator .

How do you split a string without delimiter?

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.


2 Answers

No, because according to the relevant javadoc "trailing empty strings will be discarded".

like image 155
Kim Stebel Avatar answered Oct 17 '22 22:10

Kim Stebel


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", ""}
like image 45
srkavin Avatar answered Oct 17 '22 22:10

srkavin