Read numbers from the console given in a single li

2019-01-17 22:46发布

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.

5条回答
劳资没心,怎么记你
2楼-- · 2019-01-17 23:11

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.

查看更多
Root(大扎)
3楼-- · 2019-01-17 23:11

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
    }
}
查看更多
成全新的幸福
4楼-- · 2019-01-17 23:12

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();
查看更多
霸刀☆藐视天下
5楼-- · 2019-01-17 23:12

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
查看更多
6楼-- · 2019-01-17 23:34

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);
查看更多
登录 后发表回答