Case 1
开发者_Go百科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.
Case 1 has a single item in the b array " " - your spaces
Case 2 empty entries are being removed
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
精彩评论