2014-09-19 50 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 
相关问题