Reading a text file word by word

后端 未结 9 958
梦谈多话
梦谈多话 2020-12-10 18:58

I have a text file containing just lowercase letters and no punctuation except for spaces. I would like to know the best way of reading the file char by char, in a way that

9条回答
  •  星月不相逢
    2020-12-10 19:25

    I would do something like this:

    IEnumerable ReadWords(StreamReader reader)
    {
        string line;
        while((line = reader.ReadLine())!=null)
        {
            foreach(string word in line.Split(new [1] {' '}, StringSplitOptions.RemoveEmptyEntries))
            {
                yield return word;
            }
        }
    }
    

    If to use reader.ReadAllText it loads the entire file into your memory so you can get OutOfMemoryException and a lot of other problems.

提交回复
热议问题