kakkarot
kakkarot

Reputation: 508

Reading array elements from the same line (C#)

Is it possible to read the elements of an array from the same line (from Console) in C#? I know it's possible to read multiple inputs from the console and storing the individual parts in different variables using Split(). But I can't understand how to do it in arrays.

Code

for (int i = 0; i < arrival.Length; i++)
{
     arrival[i] = int.Parse(Console.ReadLine());

}

For example, I have to enter the elements 34 35 36 37 in the array. If I use the above mentioned code, I have to enter each element in a separate line. But what I need is, if I enter 34 35 36 37 in the Console, it must store each number as an element in the array. How to do this?

Upvotes: 0

Views: 4025

Answers (3)

amit dayama
amit dayama

Reputation: 3326

you can do it in following manner for array of type integer

string readLine=Console.ReadLine());
string[] stringArray=readLine.split(' ');
int[] intArray = new int[stringArray.Length];
for(int i = 0;i < stringArray.Length;i++)
{
// Note that this is assuming valid input
// If you want to check then add a try/catch 
// and another index for the numbers if to continue adding the others
    intArray[i] = int.parse(stringArray[i]);
}

Upvotes: 2

hmojtaba
hmojtaba

Reputation: 157

you need to read from console, split the input string, convert the splitted strings to your type (here to double), then add them to your own array:

here is the code doing what you want:

using System;
using System.Collections.Generic;
using System.Linq;

namespace test4
{
class Program
{
    static void Main(string[] args)
    {
        List<double> arrayOfDouble = new List<double>(); // the array to insert into from console

        string strData = Console.ReadLine(); // the data, exmple: 123.32, 125, 78, 10
        string[] splittedStrData = strData.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        // trim then parse to souble, then convert to double list
        List<double> dataArrayAsDouble = splittedStrData.Select((s) => { return double.Parse(s.Trim()); }).ToList();

        // add the read array to your array
        arrayOfDouble.AddRange(dataArrayAsDouble);
    }
}
}

Upvotes: 0

Bhavik Patel
Bhavik Patel

Reputation: 1464

I am not clear with question, may be you are looking for this using System;

class Program
{
    static void Main()
    {
    string s = "there is a cat";
    // Split string on spaces.
    // ... This will separate all the words.
    string[] words = s.Split(' ');
    foreach (string word in words)
    {
        Console.WriteLine(word);
    }
    }
}

Output will be

there
is
a
cat

Ref link - http://www.dotnetperls.com/split

Upvotes: 0

Related Questions