2016-11-21 181 views
0

我对以下代码感到困惑,因为我认为数组的长度(allCommands)在没有任何内容时会为0。Java:为什么数组的长度为1时什么都没有了

字符串test只有英镑符号,然后我得到后面的子字符串,然后与#拆分。

String test = "#"; 
int beginIndex = test.indexOf("#"); 
test = test.substring(beginIndex+1); 
String[] allCommands = test.split("#"); 
System.out.println("allCommands length: " + allCommands.length); // output: 1 
System.out.println("allCommands array: " + Arrays.toString(allCommands)); // output: [] 

有人可以解释这一点吗?谢谢!

+5

里面有东西 - 它是一个零长度的字符串。 –

回答

1

这是一个零长度(空)字符串,下面的程序打印0.1

String test = "#"; 
int beginIndex = test.indexOf("#"); 
test = test.substring(beginIndex+1); 
String[] allCommands = test.split("#"); 
System.out.println("allCommands length: " + allCommands.length); // output: 1 
System.out.println(allCommands[0].length()); 
System.out.println("allCommands array: " + Arrays.toString(allCommands)); 
+0

根据'String.split'的Javadoc,“结尾的空字符串因此不包含在结果数组中”。所以请解释为什么数组中有一个尾随的空字符串:) –

+0

谢谢,但是如果我设置了'test =“#s1#s2#”',那么'allCommands [0] .length()'是什么意思呢?它返回第一个字符串's1'的长度,这不是我想知道的。我想知道'allCommands'数组的长度,并且不应该计算空字符串。 – TonyGW

+0

@TonyGW上面的例子会将字符串分成两个子字符串's1'和's2'。所以,'allCommands [0] .length()'将会是'2'(s1.length()) –

1

它是一个空字符串的数组。尝试运行此:

System.out.println(Arrays.toString(new String[]{""})); 

将打印[]

1

因为当你使用test.split('#')返回数组在这种情况下,由分割器计算的字符串是空字符串,因为没有更多要分割的字符串。这个空字符串进入你的String[] allCommands,所以这就是为什么大小是1并且数组是空的。

相关问题