2013-04-15 49 views
-2

如何獲取一個字符串輸入並將其設置爲一個int數組?以字符串輸入並製作一個int數組

string input = Console.ReadLine(); 
int numb = Convert.Toint32(input);   
int[] intArray = // what do i write here to make it take the "input" length, and put the input into an int array? 
+0

你能給例如輸入字符串和輸出應該是什麼是字符串? – Floremin

+0

[將逗號分隔的字符串轉換爲int數組]的可能重複(http://stackoverflow.com/questions/1763613/convert-comma-separated-string-of-ints-to-int-array) –

回答

2

你不給太多細節,但如果輸入是一個逗號分隔的數字列表,你可以這樣做:

string input = "1,2, 3,4 ,5 ,6"; // string to simulate input 
int[] numbers = input.Split(new char[] {','}) 
        .Select(s => int.Parse(s)) 
        .ToArray(); 

這顯然炸燬如果逗號之間的任何字符串不是一個有效的整數。

0

您可以通過兩種不同的方式從字符串中獲取數組。

您可以使用split方法將字符串分解爲一個子字符串數組,然後您必須解析該數組的每個元素。這可能是你想要的,因爲它似乎你想要一個整數數組;

或者您可以將字符串轉換爲字節數組。 Means to do so have been discussed in this question。然後,如果您認爲合適,則將這些值轉換爲整數。

0
string input = Console.ReadLine(); 
int numb = Convert.ToInt32(input); 
int[] intArray = new int[numb]; 
for (int i; i < intArray.length; i++) 
{ 
    intArray[i] = numb; 
} 
0

爲了得到你可以做輸入的長度如下:

string input = Console.ReadLine(); 
    int numb = input.Length; 
    int[] intArray = new int[1]; 
    intArray[0] = numb; 
相關問題