Java:当数组中什么都没有时,为什么数组的长度是1

标签 java arrays string split

我对我编写的以下代码感到困惑,因为我认为当数组中没有任何内容时,数组的长度 (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/

相关文章:

php - 给定一组常数因子,在字符串中搜索字符串的最快方法

c# - LinqToDB 如何将枚举存储为字符串值?

java - 纪元年和周年的区别?

c - 将函数调用中的多维数组分配给变量

java - 帕斯卡三角错误输出

Python不区分大小写的文件名?

java - 无法获取命令执行的值 "lsof"

java - lombok @Builder 方法

java - 通过引用传递 HashMap

javascript - Javascript 中的拆分函数不适用于对象中的字符串