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

一世执手 提交于 2019-11-28 21:35:51

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.

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
    }
}

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();

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

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);

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!