gpt4 book ai didi

Java 字符串拆分不起作用

转载 作者:行者123 更新时间:2023-12-05 08:13:48 24 4
gpt4 key购买 nike

Java 专家,

请查看下面的拆分命令代码,让我知道为什么最后两个空值没有被捕获。

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”

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

最佳答案

它的行为与 the javadoc 中指定的一样:

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.

如果你想保留尾随的空白字符串,你可以使用 2 argument split method负限制:

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 字符串拆分不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11418039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com