现象
String testString1 = "1, 1, 0, 0, 0, 6.17, 3.50,,,,,,,,,,,,,1";
String testString2 = "1, 1, 0, 0, 0, 6.17, 3.50,,,,,,,,,,,,,";
采用默认的split方式
testString.split(",");
这两者的结果是不一致的,前者的长度是20,后者为7. 因为字符串中产生了空值。如果头和尾都有值,中间空,长度不影响。否则split结果会去掉空值。
看下split的API
/**
Splits this string around matches of the given regular expression.
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.
The string "boo:and:foo", for example, yields the following results with these expressions:
Split examples showing regex and result
:{ "boo", "and", "foo" }
o{ "b", "", ":and:f" }
形参: regex – the delimiting regular expression
返回值: the array of strings computed by splitting this string around matches of the given regular expression
抛出: PatternSyntaxException – if the regular expression's syntax is invalid
*/
public String[] split(String regex) {
return split(regex, 0, false);
}
解决方案
保留所有空值
String[] tpStrings = testString.split(",",-1);
不管空值出现在哪里,都不会丢弃
去掉所有空值
String[] tpStrings = testString.split(",+");
就是中间出现空值,也会舍弃