【问题标题】:how to read words from text file in VC#如何在VC中从文本文件中读取单词#
【发布时间】:2013-01-18 11:35:04
【问题描述】:

我想读取一个文本文件并将单词彼此分割,例如这是我的文本文件:

asd
asdc
asf
气体
asdf

现在我想读“asd”,然后是“asdc”,然后是“asf”...... 我该怎么办?

【问题讨论】:

    标签: file text dictionary word words


    【解决方案1】:

    使用 StreamReader 的 ReadLine,您可以像这样逐行读取:

    使用系统; 使用 System.IO;

    类测试 {

    public static void Main() 
    {
    
        try 
        {
    
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader("TestFile.txt")) 
            {
                String line;
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((line = sr.ReadLine()) != null) 
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e) 
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
    

    }

    【讨论】:

      【解决方案2】:
      List<string> words = new List<string>();
      string line;
      char[] sep = new char[] { ' ', '\t' };
      
      try
      {
          System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
          while ((line = file.ReadLine()) != null)
          {
              words.AddRange(line.Split(sep, StringSplitOptions.RemoveEmptyEntries));  
          }
          file.Close();
      }
      catch(Exception ex)
      {
          Console.WriteLine(ex.Message);
      }
      

      此代码逐行读取文本文件并将每一行分隔为单词(按空格和制表符)。您必须自己处理异常。

      【讨论】:

      • 对不起,我是新手,你能给我更多帮助吗?
        我如何在列表框中打印它们?
      • 您只需将C:\\test.txt 替换为文件路径,结果将作为字符串列表包含在words 变量中:)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-09
      • 2011-04-12
      • 2017-04-17
      • 2017-04-15
      • 2016-02-12
      • 1970-01-01
      相关资源
      最近更新 更多