Read numbers from the console given in a single line, separated by a space
Solution 1:
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
.
Solution 2:
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
}
}
Solution 3:
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();
Solution 4:
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