Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String, split. need help understanding

Tags:

java

string

split

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

like image 305
James Raitsev Avatar asked Jul 13 '10 22:07

James Raitsev


1 Answers

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.

like image 148
Mark Byers Avatar answered Sep 30 '22 13:09

Mark Byers