我对我编写的以下代码感到困惑,因为我认为当数组中没有任何内容时,数组的长度 (allCommands
) 将为 0。
字符串 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: []
有人能解释一下吗?谢谢!
最佳答案
这是一个零长度(空)字符串,下面的程序打印 0。
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));
关于Java:当数组中什么都没有时,为什么数组的长度是1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40729243/