在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个空。我需要保留空箱。不知道我做错了什么。我也尝试过以这种方式使用拆分。 ... split("\\|",-1);
但返回长度为1的整个字符串。
非常感谢任何帮助!
答案 0 :(得分:5)
split的默认行为是不返回空标记(因为零限制)。使用限制为-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]); }
}
}
输出如下:
Length:11
0
1
2
3
4
5
6
7
8
--- BLANK LINE --
--- BLANK LINE --
“--- BLANK LINE - ”由我输入,表明返回为空白。 8 |之后空标记为空白一次一次用于最后一个|。
之后的空尾随令牌希望这可以解决问题。
答案 1 :(得分:4)
答案 2 :(得分:1)
我的Java有点生疏,但不应该是:
String currentString[] = "0|1|2|3|4|5|6|7|8||".split("\\|");
System.out.println("Length:"+currentString.length);
for(int i = 0; i < currentString.length; i++)
{
System.out.println(currentString[i]);
}
答案 3 :(得分:0)
您需要使用indexOf()
然后使用substring()
才能生效。我不认为你只能使用split()
来清空字符串。
答案 4 :(得分:0)
IMO,我认为这是拆分的默认行为,无论如何请试试这个:
String currentString [] = br.readLine()。replace(“||”,“||”)。split(“\ |”); 的System.out.println( “长:” + currentString.length); for(int i = 0; i&lt; currentString.length; i ++){ 的System.out.println(currentString [I]); }
尚未经过测试,但我认为这应该可以解决问题。
答案 5 :(得分:0)
请检查以下代码,我使用了您的解决方案,它有效:
public class SplitTest
{
public static void main(String[] args)
{
String text = "0|1|2|3|4|5|6|7|8||";
String pattern = "\\|";
String [] array = text.split(pattern, -1);
System.out.println("array length:" + array.length);
for(int i=0; i< array.length; i++)
System.out.print(array[i]+ " ");
}
}
输出是:
array length:11 0 1 2 3 4 5 6 7 8