Confusing output from String.split

sanket patel picture sanket patel · Jul 31, 2014 · Viewed 7.4k times · Source

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

Answer

Marco Acierno picture Marco Acierno · Jul 31, 2014

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