Java String拆分无法正常工作 [英] Java String split is not working
问题描述
Java专家,
请查看以下拆分命令代码,让我知道为什么不捕获最后两个空值。
Please look into the below split command code and let me know why last two nulls are not captured.
String test = "1,O1,,,,0.0000,0.0000,,";
String[] splittest = test.split(",");
System.out.println("length -"+splittest.length);
for (String string : splittest) {
System.out.println("value"+string);
}
我得到的结果
length -7
value1
valueO1
value
value
value
value0.0000
value0.0000
令人惊讶的是长度是7,因为它应该是9,你也可以看到0.0000之后的值,即两个最后的空值未到来。让我们说现在,如果我改变字符串测试
1,O1 ,,,, 0.0000,0.0000,0,0
surprisingly the length is 7 where as it should be 9 and also as you can see values after 0.0000 ie two last nulls are not coming . Lets say now if i change the string test "1,O1,,,,0.0000,0.0000,0,0"
String test = "1,O1,,,,0.0000,0.0000,0,0";
String[] splittest = test.split(",");
System.out.println("length -"+splittest.length);
for (String string : splittest) {
System.out.println("value"+string);
}
我收到了正确
length -9
value1
valueO1
value
value
value
value0.0000
value0.0000
value0
value0
我不认为我在做什么错了。这是一个错误吗? JAVA版本 - jdk1.6.0_31
I don't think iam doing wrong . Is it a bug ? JAVA Version - jdk1.6.0_31
推荐答案
它的行为与 javadoc :
此方法的作用就像通过调用给定表达式和limit参数为零的双参数split方法一样。 结果数组中不包含尾随空字符串。
如果要保留尾随空白字符串,你可以使用 2参数拆分方法,带有负限制:
If you want to keep the trailing blank strings, you can use the 2 argument split method with a negative limit:
String[] splittest = test.split(",", -1);
如果限制为非正数,则模式将应用为尽可能多次,数组可以有任何长度。
If the limit is non-positive then the pattern will be applied as many times as possible and the array can have any length.
这篇关于Java String拆分无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!