字符串数组到Int数组

Hen*_*ynx 1 c# arrays

我试图从控制台获取一个字符串,并将所有元素放在一个int数组中.它抛出一个错误,我的输入格式错误.我正在尝试"1 1 3 1 2 2 0 0",我需要那些作为int值,然后用它们执行一些计算.

这是我的尝试:

class Program
{
   static void Main()
   {

    string first = Console.ReadLine();
    string[] First = new string[first.Length];

    for (int i = 0; i < first.Length; i++)
    {
        First[i] += first[i];
    }

    int[] Arr = new int[First.Length];//int array for string console values
    for (int i = 0; i < First.Length; i++)//goes true all elements and converts them into Int32
    {
        Arr[i] = Convert.ToInt32(First[i].ToString());
    }
    for (int i = 0; i < Arr.Length; i++)//print array to see what happened
    {
        Console.WriteLine(Arr[i]);
    } 
 }
}
Run Code Online (Sandbox Code Playgroud)

Jay*_*ani 6

尝试这个

string str = "1 1 3 1 2 2 0 0";
int[] array = str.Split(' ').Select(int.Parse).ToArray(); 
Run Code Online (Sandbox Code Playgroud)

演示版


Sat*_*pal 6

您需要使用String.Split方法将字符串与字符串' '数组中的空格分开,然后将每个元素转换为整数.您可以使用System.Linq以有效的方式迭代字符串数组

using System.Linq; //You need add reference to namespace

static void Main()
{
    string numbersStr = "1 1 3 1 2 2 0 0";
    int[] numbersArrary = numbersStr.Split(' ').Select(n => Convert.ToInt32(n)).ToArray();
}
Run Code Online (Sandbox Code Playgroud)

DEMO


Ami*_*ich 5

干得好:

class Program
{
   static void Main()
   {
       string numberStr = Console.ReadLine(); // "1 2 3 1 2 3 1 2 ...."
       string[] splitted = numberStr.Split(' ');
       int[] nums = new int[splitted.Length];

       for(int i = 0 ; i < splitted.Length ; i++)
       {
         nums[i] = int.Parse(splitted[i]);
       }
   }
}
Run Code Online (Sandbox Code Playgroud)