2014-10-01 219 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數組的字符串值。通過每次重新聲明該數組,它將刪除先前的輸入。