简体   繁体   English

从文本文件中读取数字并分隔空格

[英]Reading numbers from text file and separating white spaces

I have an external text file which has numbers in it. 我有一个带有数字的外部文本文件。 like 4 54 12 32 separated by spaces. 例如4 54 12 32,以空格分隔。 I want to be able to read all the numbers and add them to a list. 我希望能够读取所有数字并将其添加到列表中。

static void Main(string[] args)
        {
            List<int> numbers;
            numbers = new List<int>();

            StreamReader file = new StreamReader("C:\\text.txt");

            while (!file.EndOfStream)
            {
                string line = file.ReadLine();
                Console.Write(line + " ");
            }
        }

ReadLine reads the whole line so I cannot separate the individual numbers and convert them to ints and I have tried Read which reads the character code of each number rather than the number itself. ReadLine会读取整行,因此我无法分离单个数字并将其转换为int,并且我尝试了Read来读取每个数字的字符代码,而不是数字本身。

Try Splitting the line by spaces 尝试按空格分隔线

string [] numbers = file.ReadLine().Split(new char[]{' '},
                                       StringSplitOptions.RemoveEmptyEntries);

您正在寻找字符串对象的拆分方法( http://msdn.microsoft.com/fr-fr/library/System.String.Split%28v=vs.110%29.aspx )。

This method should help you. 此方法应为您提供帮助。

    public static IEnumerable<int> ReadInts(string path)
    {
        var txt = File.ReadAllText(path);
        return Regex.Split(txt, @"\s+").Select(x => int.Parse(x));
    }

You can use File.ReadAllText method: 您可以使用File.ReadAllText方法:

var numbers = File.ReadAllText("C:\\text.txt")
             .Split()
             .Where(x => x.All(char.IsDigit))
             .Select(int.Parse)
             .ToList();

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

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