简体   繁体   中英

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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