2016-11-21 91 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並且數組是空的。

相關問題