Case 1
String a = " ";
String[] b = a.split(",");
System.out.println(b.length);
Prints 1. Why?
Case 2
String a = ",,,,,,,,,,,,";
String[] b = a.split(",");
System.out.println(b.length);
Prints 0. Why?
Honestly, i am at a loss here
This behaviour is mentioned in the documentation for String.split:
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.
Your first example should give an array containing a single string containing spaces. A string containing spaces is not empty so it is included in the result.
Your second example would give an array containing lots of empty strings, but these are not included in the resulting array as mentioned in the documentation.
As to why the Java designers decided that removing trailing empty strings when limit
is zero is a good idea - I don't know. Most other programming languages / platforms do not do this. I consider it to be a "gotcha" - a feature that doesn't quite work as most people expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With