tags:

views:

73

answers:

4

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

+11  A: 

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.

Mark Byers
Note that if you you use `a.split(",", -1)` (or any negative), empty trailing components won't be removed.
Matthew Flaschen
The reason is that they wanted it to behave the same as perl.
Kevin Bourrillion
All this weirdness is part of the reason Guava has its own Splitter class.
Kevin Bourrillion
+1  A: 

Case 1 has a single item in the b array " " - your spaces

Case 2 empty entries are being removed

Biff MaGriff
A: 

Mark is correct. For more information, check out this split tutorial.

perimosocordiae
Comment not answer.
polygenelubricants
A: 

hi i m manivannan In SQL Server 2005 my db name:a table name:a column name:a(varchar(max)),b(int) values

a b

hello|howdoudo|imfine|thanks 1
h|ho|ine|ths 2 helddlo|howdddoudo|imfiddne|tdhs 3

tell me the split stored procedure to get the table looks like this for i.e., when b=1 b=2 b=3

output output output a a a hello h helddlo howdoudo ho howdddoudo
imfine ine imfiddne thanks ths tdhs

manivannan