【问题标题】:Reading in files that contain specific characters in C#在 C# 中读入包含特定字符的文件
【发布时间】:2009-12-18 12:20:40
【问题描述】:

我有一个名为C:/test.txt的文本文件:

1 2 3 4 5 6

我想使用 StreamReader 读取此文件中的每个数字。

我该怎么做?

【问题讨论】:

  • 文件会包含个数字,还是可能有其他字符?
  • 您的问题似乎与您的示例无关。数字不是特殊字符...

标签: c# .net file-io streamreader


【解决方案1】:

您真的需要使用StreamReader 来执行此操作吗?

IEnumerable<int> numbers =
    Regex.Split(File.ReadAllText(@"c:\test.txt"), @"\D+").Select(int.Parse);

(显然,如果一次性读取整个文件不切实际,那么您需要将其流式传输,但如果您能够使用File.ReadAllText,那么在我看来,这就是这样做的方法。)

为了完整起见,这里是一个流媒体版本:

public IEnumerable<int> GetNumbers(string fileName)
{
    using (StreamReader sr = File.OpenText(fileName))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            foreach (string item in Regex.Split(line, @"\D+"))
            {
                yield return int.Parse(item);
            }
        }
    }
}

【讨论】:

    【解决方案2】:
    using (StreamReader reader = new StreamReader(stream))
    {
      string contents = reader.ReadToEnd();
    
      Regex r = new Regex("[0-9]");
    
      Match m = r.Match(contents );
    
      while (m.Success) 
      {
         int number = Convert.ToInt32(match.Value);
    
         // do something with the number
    
         m = m.NextMatch();
      }
    
    }
    

    【讨论】:

    • 我的意思是解决方案很慢而不是答案(%
    【解决方案3】:

    如果您想要从文件中读取整数并将它们存储在列表中,那么类似的方法可能会奏效。

    try 
    {
      StreamReader sr = new StreamReader("C:/test.txt")) 
      List<int> theIntegers = new List<int>();
      while (sr.Peek() >= 0) 
        theIntegers.Add(sr.Read());
      sr.Close();
    }
    catch (Exception e) 
    {
       //Do something clever to deal with the exception here
    }
    

    【讨论】:

      【解决方案4】:

      大文件的解决方案:

      class Program
      {
          const int ReadBufferSize = 4096;
      
          static void Main(string[] args)
          {
              var result = new List<int>();
      
              using (var reader = new StreamReader(@"c:\test.txt"))
              {
                  var readBuffer = new char[ReadBufferSize];
                  var buffer = new StringBuilder();
      
                  while ((reader.Read(readBuffer, 0, readBuffer.Length)) > 0)
                  {
                      foreach (char c in readBuffer)
                      {
                          if (!char.IsDigit(c))
                          {
                              // we found non digit character
                              int newInt;
                              if (int.TryParse(buffer.ToString(), out newInt))
                              {
                                  result.Add(newInt);
                              }
      
                              buffer.Remove(0, buffer.Length);
                          }
                          else
                          {
                              buffer.Append(c);
                          }
                      }
                  }
      
                  // check buffer
                  if (buffer.Length > 0)
                  {
                      int newInt;
                      if (int.TryParse(buffer.ToString(), out newInt))
                      {
                          result.Add(newInt);
                      }
                  }
              }
      
              result.ForEach(Console.WriteLine);
              Console.ReadKey();
          }
      }
      

      【讨论】:

        【解决方案5】:

        我可能错了,但使用 StreamReader 你不能设置分隔符。 但是您可以使用 String.Split() 设置分隔符(在您的情况下是空格?)并将所有数字提取到单独的数组中。

        【讨论】:

          【解决方案6】:

          这样的事情应该可以工作:

          using (var sr = new StreamReader("C:/test.txt"))
          {
              var s = sr.ReadToEnd();
              var numbers = (from x in s.Split('\n')
                             from y in x.Split(' ')
                             select int.Parse(y));
          }
          

          【讨论】:

            【解决方案7】:

            类似这样的:

            using System;
            using System.IO;
            
            class Test 
            {
            
                public static void Main() 
            {
                string path = @"C:\Test.txt";
            
                try 
                {
                  if( File.Exists( path ) )
                  {
                    using( StreamReader sr = new StreamReader( path ) )
                    {
                      while( sr.Peek() >= 0 )
                      {
                        char c = ( char )sr.Read();
                        if( Char.IsNumber( c ) )
                          Console.Write( c );
                      }
                    }
                  }
                } 
                catch (Exception e) 
                {
                    Console.WriteLine("The process failed: {0}", e.ToString());
                }
            }
            }
            

            【讨论】:

            • 呃...也许我在这里遗漏了一些东西(天气很冷,我的大脑不喜欢寒冷)。为什么要删除输入文件,然后尝试打开它?
            • 啊,你说得对 xD 我写得很快,而智能感知让我开玩笑:)
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-08-14
            • 1970-01-01
            • 2022-11-10
            相关资源
            最近更新 更多