2014-04-21 21 views
0

我想從控制檯獲取一個字符串,並將所有元素放在一個int數組中。 它引發錯誤,我的輸入格式錯誤。我正在嘗試使用「1 1 3 1 2 2 0 0」,我需要這些值作爲整型值,然後對它們進行一些計算。字符串數組到內部數組

這裏是我的嘗試:

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

回答

2

在這裏你去:

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]); 
     } 
    } 
} 
3

試試這個

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

Demo

5

您需要使用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(); 
} 

DEMO

1

嘗試將其更改爲這樣:

string s = Console.ReadLine(); 
string[] arr = s.Split(' '); //Split the single string into multiple strings using space as delimiter 
int[] intarr = new int[arr.Length]; 

for(int i=0;i<arr.Length;i++) 
{ 
    intarr[i] = int.Parse(arr[i]); //Parse the string as integers and fill the integer array 
} 

for(int i=0;i<arr.Length;i++) 
{ 
    Console.Write(intarr[i]); 
} 
1

您沒有使用分割空間的分隔符的字符串。

 string first = Console.ReadLine(); 
     int len = first.Split(new [] 
         {' '},StringSplitOptions.RemoveEmptyEntries).Length; 
     string[] First = new string[len]; 

     for (int i = 0; i < len; i++) 
     { 
      First[i] = first.Split(' ')[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]); 
     } 
1

你不能嘗試用 「1 1 3 1 2 2 0 0」,因爲它正試圖解析數之間的空間。如果你想讓你的程序工作,你必須使你的輸入字符串像這樣:「11312200」,或者你可以創建一個字符數組或者只是一個字符,如果你沒有多於一個分隔符,然後分配字符串。通過將分離器,這樣的:

string Numbers = "1 1 3 1"; 

string[] seperatedNumbers = Numbers.Split(' '); 

// perform your following actions 
+0

你應該分配給'的String []'變量在第二行。 –