Java:为什么使用数组';当其中没有任何内容时,s的长度为1

Java:为什么使用数组';当其中没有任何内容时,s的长度为1,java,arrays,string,split,Java,Arrays,String,Split,我对我编写的以下代码感到困惑,因为我认为数组的长度(allCommands)将是0,而其中没有任何内容 字符串test中只有英镑符号,然后我得到它后面的子字符串,后面是用#拆分的子字符串 有人能解释一下吗?谢谢 它是一个由一个空字符串组成的数组。尝试运行以下命令: System.out.println(Arrays.toString(new String[]{""})); 它将打印一个由一个空字符串组成的数组。尝试运行以下命令: System.out.println(Arrays.toStri

我对我编写的以下代码感到困惑,因为我认为数组的长度(
allCommands
)将是0,而其中没有任何内容

字符串
test
中只有英镑符号,然后我得到它后面的子字符串,后面是用
#
拆分的子字符串


有人能解释一下吗?谢谢

它是一个由一个空字符串组成的数组。尝试运行以下命令:

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

它将打印一个由一个空字符串组成的数组。尝试运行以下命令:

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

它是一个零长度(空)字符串,在程序打印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));
它是一个零长度(空)字符串,下面的程序打印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));

因为当您使用
test.split('#')
时,它会返回一个由拆分器计算的字符串数组,在本例中,该数组是空字符串,因为没有更多要拆分的内容。这个空字符串进入您的
string[]allCommands
中,这就是为什么大小为1而数组为空。

因为当您使用
test.split('#')
时,它返回一个由拆分器计算的字符串数组,在本例中它是空字符串,因为没有更多的内容要拆分。这个空字符串进入您的
string[]allCommands
,这就是为什么大小为1,数组为空。

其中有一些东西-它是零长度字符串。其中有一些东西-它是零长度字符串。根据
string.split的Javadoc,“因此,结果数组中不包括尾随空字符串。”因此请解释为什么数组中有尾随空字符串:)谢谢,但如果我设置
test=“#s1#s2#”
,那么
allCommands[0].length()
那么是什么意思?它返回第一个字符串的长度
s1
,这不是我想知道的。我想知道
allCommands
数组的长度,空字符串不应该被计算。@TonyGW上面的示例将字符串分成两个子字符串
s1
s2
。因此,
allCommands[0].length()
将是
2
(s1.length())@DarshanMehta,是的,我意识到了,但这不是我想知道的,而是我想知道数组的长度:(谢谢!@AndyTurner我们正在尝试用一些字符分割空的
字符串
。由于该
字符串
中不存在该字符,split按原样返回
字符串。:)根据
字符串的Javadoc。split
,“因此,结果数组中不包括尾随的空字符串。“所以请解释为什么数组中有一个尾随的空字符串:)谢谢,但是如果我设置
test=“#s1#s2#”
,那么
allCommands[0].length()的意思是什么?它返回第一个字符串的长度
s1
,这不是我想要知道的。我想知道
allCommands
数组的长度,空字符串不应该被计数。@上面的例子将字符串分成两个子字符串
s1
s2
。所以,
allCommands[0].length()
将是
2
(s1.length())@DarshanMehta,是的,我意识到了,但这不是我想知道的,而是我想知道数组的长度:(谢谢!@AndyTurner我们正在尝试使用某些字符拆分空的
字符串
。由于该
字符串中不存在该字符,拆分将按原样返回
字符串
。)