Confusing output from String.split

JavaRegexStringClassCore

Java Problem Overview


I do not understand the output of this code:

public class StringDemo{              
    public static void main(String args[]) {
        String blank = "";                    
        String comma = ",";                   
        System.out.println("Output1: "+blank.split(",").length);  
        System.out.println("Output2: "+comma.split(",").length);  
    }
}

And got the following output:

Output1: 1 
Output2: 0

Java Solutions


Solution 1 - Java

Documentation:

For: System.out.println("Output1: "+blank.split(",").length);

> The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

It will simply return the entire string that's why it returns 1.


For the second case, String.split will discard the , so the result will be empty.

String.split silently discards trailing separators

see guava StringsExplained too

Solution 2 - Java

Everything happens according to plan, but let's do it step by step (I hope you have some time).

According to documentation (and source code) of split(String regex) method:

> This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero.

So when you invoke

split(String regex)

you are actually getting result from the split(String regex, int limit) method which is invoked in a way:

split(regex, 0)

So here limit is set to 0.

You need to know a few things about this parameter:

  • If limit is positive you are limiting length of result array to a positive number you specified, so "axaxaxaxa".split("x",2) will return an array, ["a", "axaxaxa"], not ["a","a","a","a","a"].

  • If limit is 0 then you are not limiting the length of the result array. But it also means that any trailing empty strings will be removed. For example:

     "fooXbarX".split("X")
    

will at start generate an array which will look like:

    ["foo", "bar", ""]

("barX" split on "X" generates "bar" and ""), but since split removes all trailing empty string, it will return

    ["foo", "bar"]
  • Behaviour of negative value of limit is similar to behaviour where limit is set to 0 (it will not limit length of result array). The only difference is that it will not remove empty strings from the end of the result array. In other words

     "fooXbarX".split("X",-1)
    

will return ["foo", "bar", ""]


Lets take a look at the case,

",".split(",").length

which (as explained earlier) is same as

",".split(",", 0).length

This means that we are using a version of split which will not limit the length of the result array, but will remove all trailing empty strings, "". You need to understand that when we split one thing we are always getting two things.

In other words, if we split "abc" in place of b, we will get "a" and "c".
The tricky part is to understand that if we split "abc" in c we will get "ab" and "" (empty string).

Using this logic, if we split "," on , we will get "" and "" (two empty strings).

You can check it using split with negative limit:

for (String s: ",".split(",", -1)){
	System.out.println("\""+s+"\"");
}

which will print

""
""

So as we see result array here is at first ["", ""].

But since by default we are using limit set to 0, all trailing empty strings will be removed. In this case, the result array contains only trailing empty strings, so all of them will be removed, leaving you with empty array [] which has length 0.


To answer the case with

"".split(",").length

you need to understand that removing trailing empty strings makes sense only if such trailing empty strings ware result of splitting (and most probably are not needed).
So if there were not any places on which we could split, there is no chance that empty strings ware created, so there is no point in running this "cleaning" process.

This information is mentioned in documentation of split(String regex, int limit) method where you can read:

> If the expression does not match any part of the input then the resulting array has just one element, namely this string.

You can also see this behaviour in source code of this method (from Java 8):

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2316">2316</a>      public http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String%5B%5D" title="java.lang.String[]">String[] split(http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String" title="java.lang.String">String regex, int limit) {
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2317">2317</a> /* fastpath if the regex is a
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2318">2318</a> (1)one-char String and this character is not one of the
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2319">2319</a> RegEx's meta characters ".$|()[{^?*+\", or
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2320">2320> (2)two-char String and the first char is the backslash and
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2321">2321> the second is not the ascii digit or ascii letter.
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2322">2322> /
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2323">2323> char ch = 0;
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2324">2324> if (((regex.value.length == 1 &&
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2325">2325> ".$|()[{^?
+\".http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String.indexOf%28int%29" title="java.lang.String.indexOf(int) : int">indexOf(ch = regex.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String.charAt%28int%29" title="java.lang.String.charAt(int) : char">charAt(0)) == -1) ||
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2326">2326> (regex.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String.length%28%29" title="java.lang.String.length() : int">length() == 2 &&
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2327">2327> regex.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String.charAt%28int%29" title="java.lang.String.charAt(int) : char">charAt(0) == '\' &&
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2328">2328> (((ch = regex.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String.charAt%28int%29" title="java.lang.String.charAt(int) : char">charAt(1))-'0')|('9'-ch)) < 0 &&
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2329">2329> ((ch-'a')|('z'-ch)) < 0 &&
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2330">2330> ((ch-'A')|('Z'-ch)) < 0)) &&
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2331">2331> (ch < http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/Character.java#Character.0MIN_HIGH_SURROGATE" title="char MIN_HIGH_SURROGATE" class="hidden">Character.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/Character.java#Character.0MIN_HIGH_SURROGATE" title="char MIN_HIGH_SURROGATE" class="hidden">MIN_HIGH_SURROGATE ||
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2332">2332> ch > http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/Character.java#Character.0MAX_LOW_SURROGATE" title="char MAX_LOW_SURROGATE" class="hidden">Character.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/Character.java#Character.0MAX_LOW_SURROGATE" title="char MAX_LOW_SURROGATE" class="hidden">MAX_LOW_SURROGATE))
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2333">2333> {
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2334">2334> int off = 0;
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2335">2335> int next = 0;
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2336">2336> boolean limited = limit > 0;
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2337">2337> http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/ArrayList.java#ArrayList" title="java.util.ArrayList">ArrayList<http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String" title="java.lang.String">String> list = new http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/ArrayList.java#ArrayList" title="java.util.ArrayList">ArrayList<>();
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2338">2338> while ((next = http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String.indexOf%28int%2Cint%29" title="java.lang.String.indexOf(int,int) : int">indexOf(ch, off)) != -1) {
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2339">2339> if (!limited || list.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/ArrayList.java#ArrayList.size%28%29" title="java.util.ArrayList.size() : int">size() < limit - 1) {
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2340">2340> list.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/ArrayList.java#ArrayList.add%28java.lang.String%29" title="java.util.ArrayList.add(java.lang.String) : boolean">add(http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String.substring%28int%2Cint%29" title="java.lang.String.substring(int,int) : String">substring(off, next));
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2341">2341> off = next + 1;
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2342">2342> } else { // last one
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2343">2343> //assert (list.size() == limit - 1);
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2344">2344> list.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/ArrayList.java#ArrayList.add%28java.lang.String%29" title="java.util.ArrayList.add(java.lang.String) : boolean">add(http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String.substring%28int%2Cint%29" title="java.lang.String.substring(int,int) : String">substring(off, http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String.0value" title="char[] value" class="hidden">value.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String.0value" title="char[] value" class="hidden">length));
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2345">2345> off = http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String.0value" title="char[] value" class="hidden">value.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String.0value" title="char[] value" class="hidden">length;
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2346">2346> break;
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2347">2347> }
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2348">2348> }
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2349">2349> // If no match was found, return this
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2350">2350> if (off == 0)
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2351">2351> return new http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String" title="java.lang.String">String[]{this};
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2353">2353> // Add remaining segment
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2354">2354> if (!limited || list.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/ArrayList.java#ArrayList.size%28%29" title="java.util.ArrayList.size() : int">size() < limit)
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2355">2355> list.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/ArrayList.java#ArrayList.add%28java.lang.String%29" title="java.util.ArrayList.add(java.lang.String) : boolean">add(http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String.substring%28int%2Cint%29" title="java.lang.String.substring(int,int) : String">substring(off, http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String.0value" title="char[] value" class="hidden">value.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String.0value" title="char[] value" class="hidden">length));
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2357">2357> // Construct result
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2358">2358> int resultSize = list.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/ArrayList.java#ArrayList.size%28%29" title="java.util.ArrayList.size() : int">size();
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2359">2359> if (limit == 0) {
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2360">2360> while (resultSize > 0 && list.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/ArrayList.java#ArrayList.get%28int%29" title="java.util.ArrayList.get(int) : String">get(resultSize - 1).http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String.length%28%29" title="java.lang.String.length() : int">length() == 0) {
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2361">2361> resultSize--;
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2362">2362> }
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2363">2363> }
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2364">2364> http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String%5B%5D" title="java.lang.String[]">String[] result = new http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#String" title="java.lang.String">String[resultSize];
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2365">2365> return list.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/ArrayList.java#ArrayList.subList%28int%2Cint%29" title="java.util.ArrayList.subList(int,int) : List">subList(0, resultSize).http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/List.java#List.toArray%28java.lang.String%5B%5D%29" title="java.util.List.toArray(java.lang.String[]) : String[]">toArray(result);
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2366">2366> }
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2367">2367> return Pattern.http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/regex/Pattern.java#Pattern.compile%28java.lang.String%29" title="java.util.regex.Pattern.compile(java.lang.String) : Pattern">compile(regex).http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/regex/Pattern.java#Pattern.split%28java.lang.CharSequence%2Cint%29" title="java.util.regex.Pattern.split(java.lang.CharSequence,int) : String[]">split(this, limit);
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#2368">2368> }

where you can find

if (off == 0)
    return new String[]{this};

fragment which means

  • if (off == 0) - if off (position from which method should start searching for next possible match for regex passed as split argument) is still 0 after iterating over entire string, we didn't find any match, so the string was not split
  • return new String[]{this}; - in that case let's just return an array with original string (represented by this).

Since "," couldn't be found in "" even once, "".split(",") must return an array with one element (empty string on which you invoked split). This means that the length of this array is 1.

BTW. Java 8 introduced another mechanism. It removes leading empty strings (if they ware created while splitting process) if we split using zero-length regex (like "" or with look-around (?<!x)). More info at: https://stackoverflow.com/questions/22718744/why-in-java-8-split-sometimes-removes-empty-strings-at-start-of-result-array

Solution 3 - Java

From the Java 1.7 Documentation

>Splits the string around matches of the given regular expression. > >split() method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

In the Case 1 blank.split(",") does not match any part of the input then the resulting array has just one element, namely this String.

It will return entire String. So, the length will be 1.

In the Case 2 comma.split(",") will return empty.

split() expecting a regex as argument, return result array to matching with that regex.

So, the length is 0

For Example(Documentation) >The string "boo:and:foo", yields the following results with these expressions:

Regex 	  Result
  : 	{ "boo", "and", "foo" }
  o 	{ "b", "", ":and:f" }

>Parameters: > regex - the delimiting regular expression > >Returns: > the array of strings computed by splitting this string around matches of the given regular expression > >Throws: > PatternSyntaxException - if the regular expression's syntax is invalid

Solution 4 - Java

From String class javadoc for the public String[] split(String regex) method:

>Splits this string around matches of the given regular expression.
> >This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

In the first case, the expression does not match any part of the input so we got an array with only one element - the input.

In the second case, the expression matches input and split should return two empty strings; but, according to javadoc, they are discarded (because they are trailing and empty).

Solution 5 - Java

We can take a look into the source code of java.util.regex.Pattern which is behind String.split. Way down the rabbit hole the method

public String[] split(CharSequence input, int limit)

is invoked.

Input ""

For input "" this method is called as

String[] parts = split("", 0);

The intersting part of this method is:

  int index = 0;
  boolean matchLimited = limit > 0;
  ArrayList<String> matchList = new ArrayList<>();
  Matcher m = matcher(input);

  while(m.find()) {
    // Tichodroma: this will not happen for our input
  }

  // If no match was found, return this
  if (index == 0)
    return new String[] {input.toString()};

And that is what happens: new String[] {input.toString()} is returned.

Input ","

For input "," the intersting part is

    // Construct result
    int resultSize = matchList.size();
    if (limit == 0)
        while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
            resultSize--;
    String[] result = new String[resultSize];
    return matchList.subList(0, resultSize).toArray(result);

Here resultSize == 0 and limit == 0 so new String[0] is returned.

Solution 6 - Java

From JDK 1.7

 public String[] split(String regex, int limit) {
        /* fastpath if the regex is a
           (1)one-char String and this character is not one of the
              RegEx's meta characters ".$|()[{^?*+\\", or
           (2)two-char String and the first char is the backslash and
              the second is not the ascii digit or ascii letter.
        */
        char ch = 0;
        if (((regex.count == 1 &&
             ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
             (regex.length() == 2 &&
              regex.charAt(0) == '\\' &&
              (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
              ((ch-'a')|('z'-ch)) < 0 &&
              ((ch-'A')|('Z'-ch)) < 0)) &&
            (ch < Character.MIN_HIGH_SURROGATE ||
             ch > Character.MAX_LOW_SURROGATE))
        {
            int off = 0;
            int next = 0;
            boolean limited = limit > 0;
            ArrayList<String> list = new ArrayList<>();
            while ((next = indexOf(ch, off)) != -1) {
                if (!limited || list.size() < limit - 1) {
                    list.add(substring(off, next));
                    off = next + 1;
                } else {    // last one
                    //assert (list.size() == limit - 1);
                    list.add(substring(off, count));
                    off = count;
                    break;
                }
            }
            // If no match was found, return this
            if (off == 0)
                return new String[] { this };

            // Add remaining segment
            if (!limited || list.size() < limit)
                list.add(substring(off, count));

            // Construct result
            int resultSize = list.size();
            if (limit == 0)
                while (resultSize > 0 && list.get(resultSize-1).length() == 0)
                    resultSize--;
            String[] result = new String[resultSize];
            return list.subList(0, resultSize).toArray(result);
        }
        return Pattern.compile(regex).split(this, limit);
    }

So for this case, the regex will be handled by the first if.

For the first case blank.split(",")

// If no match was found, return this
if (off == 0)
   return new String[] { this };

So, this function will return an array which contains one element if there is no matched.

For the second case comma.split(",")

List<String> list = new ArrayList<>();
//...
int resultSize = list.size();
if (limit == 0)
    while (resultSize > 0 && list.get(resultSize-1).length() == 0)
           resultSize--;
String[] result = new String[resultSize];
return list.subList(0, resultSize).toArray(result);

As you notice, the last while loop has removed all empty element in the end of the list, so the resultSize is 0.

Solution 7 - Java

String blank = "";                    
String comma = ",";                   
System.out.println("Output1: "+blank.split(",").length);  // case 1
System.out.println("Output2: "+comma.split(",").length);  // case 2

case 1 - Here blank.split(",") will return "" since there is no , in blank you get the same, So length will be 1

case 2- Here comma.split(",") will return empty array, you have to scape , if you want to count comma with length 1 else length will be 0

Again comma.split(",") split() expecting a regex as argument it will return result array to matching with that regex.

> The array returned by this method contains each substring of this > string that is terminated by another substring that matches the given > expression or is terminated by the end of the string.

Else

> If the expression does not match any part of the input then the > resulting array has just one element, namely this string.

Solution 8 - Java

The API for the split method states that "If the expression does not match any part of the input then the resulting array has just one element, namely this string."

So, as the String blank doesn't contain a ",", a String[] with one element (i.e. blank itself) is returned.

For the String comma, "nothing" is left of the original string thus an empty array is returned.

This seems to be the best solution if you want to process the returned result, e. g.

String[] splits = aString.split(",");
for(String split: splits) {
   // do something
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsanket patelView Question on Stackoverflow
Solution 1 - JavaMarco AciernoView Answer on Stackoverflow
Solution 2 - JavaPshemoView Answer on Stackoverflow
Solution 3 - JavaNaveen Kumar AloneView Answer on Stackoverflow
Solution 4 - JavaIvan NikolaevView Answer on Stackoverflow
Solution 5 - Javauser1907906View Answer on Stackoverflow
Solution 6 - JavaPham TrungView Answer on Stackoverflow
Solution 7 - JavaRuchira Gayan RanaweeraView Answer on Stackoverflow
Solution 8 - JavaRalf WagnerView Answer on Stackoverflow