繁体   English   中英

创建新的空字符串数组

[英]Creating new and empty string array

我试图用空格分隔命令行输入。

for (int len = 4; len > 0; len--) {
   int command = System.in.read(cmdString);
   String commandWhole = new String(cmdString); //Gives us a string that we can parse
   String[] commandPieces = commandWhole.split("\\s*+");
}

如果输入“ hello world”,则将具有commandPieces [0] =“ hello”和commandPieces [1] =“ world”。 那很完美。 但是,如果我随后输入“ test”,则将具有commandPieces [0] =“ test”和commandPieces [1] =“ world”,但我不希望有commandPieces [1]。

我如何为for循环的每次迭代创建一个新的String数组。 就像是:

String[] commandPieces = new String[]{commandWhole.split("\\s*+")};

这显然不起作用,因为split返回一个字符串数组。

谢谢

有一个更简单的方法

  String[] commPice = wholeCommand.split(what ever);

阵列将自动创建

您可以使用这种类型的代码

public class TestSplitScanner {

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int noOfTimestoReadFrom = 4;

      for (int i = 0; i < noOfTimestoReadFrom; i++) {
        String next = scanner.nextLine();
        String[] split = next.split("\\s+");
        System.out.println(Arrays.toString(split));

       }

     }

}

我将总结我从问题中的评论中学到的东西。 我没有对每次迭代创建一个新的commandPieces数组,而是对其进行了更改,以使每次迭代都重置cmdString数组。 现在的代码如下所示:

for (int len = 4; len > 0; len--) {
   byte cmdString[] = new byte[MAX_LEN];
   int command = System.in.read(cmdString);
   String commandWhole = new String(cmdString); //Gives us a string that we can parse
   String[] commandPieces = commandWhole.split("\\s*+");
}

阅读文档以供阅读时,输入的每一行均以字节形式存储在cmdString中。 因此,输入“ hello world”将“ hello world”存储在cmdString数组中。 然后输入“ test”将更改cmdString的前几个字节,但长度不足以覆盖“ world”。

每次迭代时,commandPieces都会拆分cmdString数组的字符串值。 通过每次重新声明此数组,它将删除先前的输入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM