Read numbers from the console given in a single line, separated by a space

tabula picture tabula · Jan 21, 2015 · Viewed 44.1k times · Source

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.

Answer

Tim Schmelter picture Tim Schmelter · Jan 21, 2015

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.