Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String array to Int array

Tags:

arrays

c#

I am trying to get a string from the console and put all elements in an int array. It throws an error that my input was in a wrong format. I am trying with "1 1 3 1 2 2 0 0" and I need those as int values and later perform some calculations with them.

Here is my attempt:

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]);
    } 
 }
}
like image 935
Henry Lynx Avatar asked Apr 21 '14 07:04

Henry Lynx


People also ask

How do I turn a string of numbers into an array?

To convert an array of strings to an array of numbers:Use the forEach() method to iterate over the strings array. On each iteration, convert the string to a number and push it to the numbers array.

How do I convert a string to an int?

Use Integer.parseInt() to Convert a String to an Integer This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.

Can we convert string to array in C?

Create an empty array with size as string length and initialize all of the elements of array to zero. Start traversing the string. Check if the character at the current index in the string is a comma(,). If yes then, increment the index of the array to point to the next element of array.


1 Answers

try this

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

Demo

like image 191
Jayesh Goyani Avatar answered Oct 12 '22 13:10

Jayesh Goyani