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.
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):or, if you want to use only spaces as delimiter:
If you want to parse them to
int
you can useArray.ConvertAll()
:If you want to check if the format is valid use
int.TryParse
.You can split the line using
String.Split()
:You can use Linq to read the line then split and finally convert each item to integers:
You simply need to split the data entered.
This will help you to remove extra blank spaces present at the end or beginning of the input string.