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]);
}
}
}
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.
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.
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.
try this
string str = "1 1 3 1 2 2 0 0";
int[] array = str.Split(' ').Select(int.Parse).ToArray();
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With