我试图用空格从命令行拆分输入。
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] ="你好"和commandPieces [1] =" world"。那是完美的。但是,如果我输入" test"我将拥有commandPieces [0] =" test"和commandPieces [1] ="世界"但我不希望那里有一个命令[1]。
如何为for循环的每次迭代创建一个新的String数组。 类似的东西:
String[] commandPieces = new String[]{commandWhole.split("\\s*+")};
显然因为split返回字符串数组而无法工作。
由于
答案 0 :(得分:0)
有一种更简单的方式
String[] commPice = wholeCommand.split(what ever);
将自动创建数组
答案 1 :(得分:0)
您可以使用此类代码
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));
}
}
}
答案 2 :(得分:0)
我只是总结一下我从问题中的评论中学到的东西。 我没有为每次迭代创建一个新的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的形式存储为字节。因此在cmdString数组中输入“hello world”存储“hello world”。然后输入“test”将改变cmdString的前几个字节,但不足以写入“world”。
每次迭代,commandPieces都会拆分cmdString数组的字符串值。通过每次重新声明此数组,它会删除以前的输入。