简体   繁体   English

如何在C#中以合理的方式从控制台读取很长的字符串并解析为数字?

[英]How can I read very long string from Console and Parse to numbers in a reasonable way in C#?

I would like to read a very long string from Console, and parse to intergers in C#. 我想从Console读取一个很长的字符串,并解析为C#中的整数。 Is there any good way to do? 有什么好办法吗?

the input looks like: 202 203 204 .. 202 输入如下:202 203 204 .. 202

and it contains 1000 numbers. 它包含1000个数字。 I need az array of integers form the input. 我需要一个z整数数组构成输入。

I know this example: 我知道这个例子:

StringBuilder sb =new StringBuilder();
while (true) {
    char ch = Convert.ToChar(Console.Read());
    sb.Append(ch);
    if (ch=='\n') {
        break;
    }
}

But is there any faster way? 但是,有什么更快的方法吗? Maybe use Readline() to read to the space separator in a loop? 也许使用Readline()循环读取空格分隔符?

Thanks ahead 提前谢谢

var array = Console.ReadLine().Split().Select(int.Parse).ToArray();

It really depends on what you want to do with invalid entries. 这实际上取决于您要对无效条目执行的操作。

var numbers = Console.ReadLine().Split(' ')
                               .Where(x => { int i; return int.TryParse(x, out i);})
                               .Select(int.Parse).ToArray();

This will just skip entries that are not ints 这只会跳过不是整数的条目

使用以下代码:

var arr = Console.ReadLine().Split(' ').Select(p=>int.Parse(p) ).ToArray();

This can give you what you want 这可以给你你想要的

List<int> inputs = new List<int>();
foreach(string o in inputText.Split(' '));//space character
{
    bool correct = false;
    //add some controls for the control if the input is correct integer
    ...
    if(correct)
        inputs.Add(Convert.ToInt32(o));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM