2014-09-19 73 views
0

我有一個用戶通過Console.ReadLine()輸入的字符串,例如「140 150 64 49」(僅用空格分隔),我想將這些數字添加到數組中。什麼是最好的方式來做到這一點。我對編程有點新,所以我有點迷路。谷歌也沒有幫助。計算字符串中的數字並將它們添加到數組中

+0

你可以通過每個單個字符循環,並嘗試將其轉換爲數字。如果轉換成功,則表示它是一個數字。 – nbro 2014-09-19 18:59:00

+0

你在用什麼語言?你試過什麼了? – Degustaf 2014-09-19 18:59:52

+0

他正在使用C#,因爲我們可以從使用C#的ReadLine() – nbro 2014-09-19 19:00:25

回答

0

當你說使用Console.ReadLine()時,我假設你使用C#。如果你不能確定有效的輸入

 int counter = 0; 
     int[] array = new int[200]; // choose some size 
     string s = Console.ReadLine(); 

     int indexOfNextSpace; 
     while ((indexOfNextSpace = s.IndexOf(' ')) > -1) 
     { 
      int num = int.Parse(s.Substring(0, indexOfNextSpace)); 
      array[counter] = num; 
      counter++; 
      s = s.Substring(indexOfNextSpace + 1); 
     } 

,嘗試嘗試\趕上週圍,或使用int.TryParse而不是int.Parse:

您可以使用此。

+0

它的工作。謝謝! – 2014-09-19 19:24:29

0

您可以使用此:

List<int> ints = new List<int>(); 
int num; 
int[] result = new int[] { }; 

string input = Console.ReadLine(); 

foreach (string str in input.Split(' ')) 
{ 
    if (int.TryParse(str, out num)) 
    { 
     ints.Add(num); 
    } 
} 

result = ints.ToArray(); 

foreach (int i in result) 
{ 
    Console.WriteLine(i); 
} 

它使用一個列表,然後將其轉換爲陣列。請注意,項目已經過驗證,因此僅添加了整數。

這將產生以下輸出:

123 456 dsf def 1 

123 
456 
1 
相關問題