Java字符串拆分功能表现奇怪

ast*_*tro 5 java string split

split()在Java中使用该方法时注意到奇怪的行为.

我有一个字符串如下: 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]);
}
Run Code Online (Sandbox Code Playgroud)

这将产生预期的结果:

Length: 11
0
1
2
3
4
5
6
7
8
9
10
Run Code Online (Sandbox Code Playgroud)

但是,如果我收到字符串: 0|1|2|3|4|5|6|7|8||

我得到以下结果:

Length: 8
0
1
2
3
4
5
6
7
8
Run Code Online (Sandbox Code Playgroud)

The final 2 empties are omitted. I need the empties to be kept. Not sure what i am doing wrong. I have also tried using the split in this manner as well. ...split("\\|",-1);

but that returns the entire string with a length of 1.

Any help would be greatly appreciated!

Gen*_*diy 5

拆分的默认行为是不返回空标记(因为零限制).使用限制为-1的两个参数split方法将在返回时为您提供所有空标记.

更新:

测试代码如下:

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]); }
  }
}
Run Code Online (Sandbox Code Playgroud)

输出如下:

Length:11
0
1
2
3
4
5
6
7
8
--- BLANK LINE --    
--- BLANK LINE --
Run Code Online (Sandbox Code Playgroud)

"--- BLANK LINE - "由我输入,表明返回为空白.8 |之后空令牌空白一次 并且一次用于最后一个|之后的空尾随令牌.

希望这可以解决问题.