我在 Java 中使用 split()
方法时注意到奇怪的行为。
我有一个字符串如下:0|1|2|3|4|5|6|7|8|9|10
String currentString[] = br.readLine().split("\\|");
System.out.println("Length:"+currentString.length);
for(int i=0;i < currentString.length;i++){
System.out.println(currentString[i]);
}
这将产生预期的结果:
Length: 11
0
1
2
3
4
5
6
7
8
9
10
但是如果我收到字符串:0|1|2|3|4|5|6|7|8||
我得到以下结果:
Length: 8
0
1
2
3
4
5
6
7
8
省略了最后 2 个空瓶。我需要保留空瓶。不知道我做错了什么。我也尝试过以这种方式使用拆分。 ...拆分("\\|",-1);
但这会返回长度为 1 的整个字符串。
如有任何帮助,我们将不胜感激!
最佳答案
split 的默认行为是不返回空标记(因为零限制)。使用限制为 -1 的两个参数拆分方法将在返回中为您提供所有空标记。
更新:
测试代码如下:
public class Test {
public static void main(String[] args) {
String currentString[] = "0|1|2|3|4|5|6|7|8||".split("\\|", -1);
System.out.println("Length:"+currentString.length);
for(int i=0;i < currentString.length;i++){ System.out.println(currentString[i]); }
}
}
输出如下:
Length:11
0
1
2
3
4
5
6
7
8
--- BLANK LINE --
--- BLANK LINE --
“--- BLANK LINE --”是我输入的,表示回车是空白。 8|之后的空token为空白一次一次用于最后一个 | 之后的空尾随标记。
希望这能解决问题。
关于Java 字符串拆分函数表现奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2039689/