2014-10-01 217 views
0

我想从命令行中用空格拆分输入。创建新的空字符串数组

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*+"); 
} 

如果I输入 “世界你好”,我将有commandPieces [0] = “你好” 和commandPieces [1] = “世界”。那很完美。但是,如果我然后输入“测试”,我会有commandPieces [0] =“测试”和commandPieces [1] =“世界”,但我不希望有一个commandPieces [1]。

如何为for循环的每次迭代创建一个新的String数组。 喜欢的东西:

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

这显然不会,因为分裂工作返回一个字符串数组。

感谢

+1

*如果我然后输入“测试”我会有commandPieces [0] =“test”和commandPieces [1] =“world”* =>你确定吗? – assylias 2014-10-01 16:56:27

+0

这绝不应该这样做,因为世界不应该在命令行参数中,如果只有测试输入 – jgr208 2014-10-01 16:58:28

+0

OP将再次使用相同的变量... – StackFlowed 2014-10-01 16:58:55

回答

0

有一个简单的方法

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

阵列将通过创建全自动

+0

isn'他在做什么? – Alboz 2014-10-01 17:00:51

+1

是的,他永远不会重置变量,为什么世界仍然在阵列中 – jgr208 2014-10-01 17:01:29

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)); 

     } 

    } 

} 
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数组的字符串值。通过每次重新声明该数组,它将删除先前的输入。