0
class Test{
    public static void main(String[] arg){
        String str1="a,,";
        String str2="a,,b";
        System.out.println(str1+" len="+str1.split(",").length);
        System.out.println(str2+" len="+str2.split(",").length);
    }
}

The output is

a,, len=1
a,,b len=3

Isn't the number of parts supposed to be 3 in both the cases?

Curious
  • 21
  • 2

4 Answers4

0

No, what you are seeing is completely normal. The best I can say is ciopy-paste the documentation:

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.

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

You need to read the documentation to understand better =)
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html

An SO User
  • 24,612
  • 35
  • 133
  • 221
0

That is the expected behavior according to the Java API.

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.

For more control, consider looking into the String#split(String, int) method.

BambooleanLogic
  • 7,530
  • 3
  • 30
  • 56
0

This example is there in oracle Documentation, this solves all the confusion.

String "boo:and:foo" Regex "o"

Result { "b", "", ":and:f" }

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

Bharath R
  • 1,491
  • 1
  • 11
  • 23
0

Try this one.

String str1="a,,";
String str2="a,,b";
System.out.println(str1+" len="+str1.split(",", -1).length);
System.out.println(str2+" len="+str2.split(",", -1).length);
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64