【问题标题】:Java: why the array's length is 1 when nothing is in itJava:为什么数组中没有任何内容时数组的长度为1
【发布时间】:2016-11-21 20:57:38
【问题描述】:

我对我编写的以下代码感到困惑,因为我认为数组的长度 (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: []

有人能解释一下吗?谢谢!

【问题讨论】:

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

标签: java arrays string split


【解决方案1】:

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

【讨论】:

  • 根据String.split 的Javadoc,“因此,结果数组中不包含尾随的空字符串。”所以请解释为什么数组中有一个尾随的空字符串:)
  • 谢谢,但是如果我设置test = "#s1#s2#",那么allCommands[0].length() 是什么意思呢?它返回第一个字符串s1 的长度,这不是我想知道的。我想知道allCommands数组的长度,空字符串不应该计算在内。
  • @TonyGW 上面的例子会将字符串分成两个子字符串s1s2。所以,allCommands[0].length() 将是 2 (s1.length())
  • @DarshanMehta,是的,我意识到了,但这不是我想知道的,而是我想知道数组的长度 :( 谢谢!
  • @AndyTurner 我们试图用一些字符分割一个空的string。由于该字符在 String 中不存在,因此 split 按原样返回 string。 :)
【解决方案2】:

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

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

它将打印[]

【讨论】:

    【解决方案3】:

    因为当您使用test.split('#') 时,它会返回一个由拆分器计算出的字符串数组,在这种情况下它是空字符串,因为没有什么要拆分的了。这个空字符串进入您的String[] allCommands,这就是为什么大小为 1 且数组为空的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      • 2020-05-22
      • 2022-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多