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
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