12

I have a task to read n given numbers in a single line, separated by a space ( ) from the console.

I know how to do it when I read every number on a separate line (Console.ReadLine()) but I need help with how to do it when the numbers are on the same line.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
tabula
  • 243
  • 1
  • 4
  • 13

7 Answers7

23

You can use String.Split. You can provide the character(s) that you want to use to split the string into multiple. If you provide none all white-spaces are assumed as split-characters(so new-line, tab etc):

string[] tokens = line.Split(); // all spaces, tab- and newline characters are used

or, if you want to use only spaces as delimiter:

string[] tokens = line.Split(' ');

If you want to parse them to int you can use Array.ConvertAll():

int[] numbers = Array.ConvertAll(tokens, int.Parse); // fails if the format is invalid

If you want to check if the format is valid use int.TryParse.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 2
    What will happen if the user enters a value followed by _two spaces_ and then a second value? Will the ConvertAll method correctly ignore the _empty_ array element? You may wish to use the overload that takes the `StringSplitOptions` enumeration and use `StringSplitOptions.RemoveEmptyEntries`. – Chris Dunaway Jan 21 '15 at 16:47
  • @ChrisDunaway: that would be a good approach. But maybe empty element are exceptional and should not be ignored silently. We don't know. – Tim Schmelter Jan 21 '15 at 21:12
8

You can split the line using String.Split():

var line = Console.ReadLine();
var numbers = line.Split(' ');
foreach(var number in numbers)
{
    int num;
    if (Int32.TryParse(number, out num))
    {
        // num is your number as integer
    }
}
Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
7

You can use Linq to read the line then split and finally convert each item to integers:

  int[] numbers = Console
        .ReadLine()
        .Split(new Char[] {' '}, StringSplitOptions.RemoveEmptyEntries)
        .Select(item => int.Parse(item))
        .ToArray();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
3

You simply need to split the data entered.

string numbersLine = console.ReadLine();

string[] numbers = numbersLine.Split(new char[] { ' '});

// Convert to int or whatever and use
Kami
  • 19,134
  • 4
  • 51
  • 63
0

This will help you to remove extra blank spaces present at the end or beginning of the input string.

string daat1String = Console.ReadLine();
daat1String = daat1String.TrimEnd().TrimStart();
string[] data1 = daat1String.Split(null);
int[] data1Int = Array.ConvertAll(data1, int.Parse);
Rupesh Kamble
  • 123
  • 2
  • 8
0

you can do

int[] Numbers  = Array.ConvertAll(Console.ReadLine().Split(' '),(item) => Convert.ToInt32(item));

the above line helps us get individual integers in a Line , separated by a Single space.Two Or More spaces between numbers will result in error.

int[] Numbers = Array.ConvertAll(Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries), (item) => Convert.ToInt32(item));

this variation will Fix the error and work well even when two or more spaces between numbers in a Line

Arvind Reddy
  • 406
  • 2
  • 10
  • While this code may solve the question, [including an explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. – Busti Mar 27 '19 at 16:27
-2

you can use this function, it's very helpful

    static List<string> inputs = new List<string>();
    static int input_pointer = 0;

    public static string cin(char sep = ' ')
    {
        if (input_pointer >= inputs.Count)
        {
            string line = Console.ReadLine();

            inputs = line.Split(sep).OfType<string>().ToList();
            input_pointer = 0;
        }

        string v = inputs[input_pointer];
        input_pointer++;

        return v;
    }

Example:

        for(var i =0; i<n ; i++)
            for (var j = 0; j<n; j++)
            {
                M[i,j] = Convert.ToInt16(cin());
            }
Sweet HD
  • 11
  • 2