5

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

7 Answers 7

18

try this

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

Demo

Sign up to request clarification or add additional context in comments.

Comments

8

You need to use String.Split Method to split your string with space' ' in an array of strings and then convert each element to integer. You can iterate string array using System.Linq in efficient manner

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

Comments

5

Here you go:

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

Comments

2

You are not splitting the string using space delimiter.

        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 Comment

This is the only answer that handles multiple spaces between numbers. GFG did this to me.
1

Try changing it to this:

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

Comments

1

You cant try with "1 1 3 1 2 2 0 0", because it is trying to parse the spaces between the numbers. If you want your program to work you have to either make your input string like that: "11312200" or you can make a char array or just a single char if you dont have more than one separator where you assign and then .split the string by passing the separator, like that:

string Numbers = "1 1 3 1";

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

// perform your following actions

1 Comment

You should assign to a String[] variable in the second line.
0

You can do this with a simple extension method:

Using:

 var stringArray = "0,1,2,3,4,5";
 stringArray.ParseIntArray();

Code:

//separator parameter: default value is ',' you can use whatever you want. ' ', '|', ';'

public static int[] ParseIntArray(this string source, char separator = ',')
{
   return Array.ConvertAll(source.Split(separator), int.Parse);
}

If you don't want to get an exception you can use this. It returns new int[] {0} when throw an exception.

Using:

var stringArray = "0,1,2,3,4,5";
stringArray.TryParseIntArray();

Code:

public static int[] TryParseIntArray(this string source, char separator = ',')
{
   int[] arrInt;

   try
     {
       arrInt = Array.ConvertAll(source.Split(separator), int.Parse);          
     }
   catch (Exception ex)
     {
       arrInt = new int[] { 0 };
     }

  return arrInt;
}

1 Comment

Thanks for the great answer - BTW surely it would be better to return an empty array as the general best choice when there's an exception?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.