【问题标题】:C#: Looping through lines of multiline stringC#:循环遍历多行字符串
【发布时间】:2010-12-02 18:43:17
【问题描述】:

什么是循环遍历多行字符串的每一行而不使用更多内存(例如不将其拆分为数组)的好方法?

【问题讨论】:

    标签: c# loops multilinestring


    【解决方案1】:

    有时我认为我们可以使解决方案过于复杂,以避免重复一行代码。这就是我首先提出这个问题的原因。

    经过一番思考,我得出结论,最简单的解决方案是在循环之前和循环内重复ReadLine。

    using (var stringReader = new StringReader(input))
    {
        var line = await stringReader.ReadLineAsync();
    
        while (line != null)
        {
            // do something
            line = await stringReader.ReadLineAsync();
        }
    }
    

    我意识到这可能被认为不遵循 DRY 原则,但考虑到简单性,我认为值得考虑。

    【讨论】:

      【解决方案2】:

      尝试使用 String.Split 方法:

      string text = @"First line
      second line
      third line";
      
      foreach (string line in text.Split('\n'))
      {
          // do something
      }
      

      【讨论】:

        【解决方案3】:

        我知道这个问题已经得到解答,但我想添加我自己的答案:

        using (var reader = new StringReader(multiLineString))
        {
            for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
            {
                // Do something with the line
            }
        }
        

        【讨论】:

        • 我喜欢这样简洁。泰。
        【解决方案4】:

        我建议使用StringReader 和我的LineReader 类的组合,它是MiscUtil 的一部分,但也可以在this StackOverflow answer 中使用 - 您可以轻松地将该类复制到您自己的实用程序项目中。你会这样使用它:

        string text = @"First line
        second line
        third line";
        
        foreach (string line in new LineReader(() => new StringReader(text)))
        {
            Console.WriteLine(line);
        }
        

        循环遍历字符串数据主体中的所有行(无论是文件还是其他)是如此普遍,以至于它不应该要求调用代码测试 null 等 :) 话虽如此,如果你 do 想要手动循环,这是我通常比 Fredrik 更喜欢的形式:

        using (StringReader reader = new StringReader(input))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                // Do something with the line
            }
        }
        

        这样您只需测试一次是否为空,并且您也不必考虑 do/while 循环(由于某种原因,这总是比直接的 while 循环花费我更多的精力阅读)。

        【讨论】:

        • 看起来 MiscUtil 没有适用于 .NET Core 的版本。
        • @void.pointer:不,我不害怕。这不是我在过去 10 年中投入任何时间的项目。
        • StringReader,一个鲜为人知的对象。谢谢。这正是我所需要的。
        【解决方案5】:

        这里有一个快速的代码 sn-p,它将在字符串中找到第一个非空行:

        string line1;
        while (
            ((line1 = sr.ReadLine()) != null) &&
            ((line1 = line1.Trim()).Length == 0)
        )
        { /* Do nothing - just trying to find first non-empty line*/ }
        
        if(line1 == null){ /* Error - no non-empty lines in string */ }
        

        【讨论】:

          【解决方案6】:

          来自 MSDN 的 StringReader

              string textReaderText = "TextReader is the abstract base " +
                  "class of StreamReader and StringReader, which read " +
                  "characters from streams and strings, respectively.\n\n" +
          
                  "Create an instance of TextReader to open a text file " +
                  "for reading a specified range of characters, or to " +
                  "create a reader based on an existing stream.\n\n" +
          
                  "You can also use an instance of TextReader to read " +
                  "text from a custom backing store using the same " +
                  "APIs you would use for a string or a stream.\n\n";
          
              Console.WriteLine("Original text:\n\n{0}", textReaderText);
          
              // From textReaderText, create a continuous paragraph 
              // with two spaces between each sentence.
              string aLine, aParagraph = null;
              StringReader strReader = new StringReader(textReaderText);
              while(true)
              {
                  aLine = strReader.ReadLine();
                  if(aLine != null)
                  {
                      aParagraph = aParagraph + aLine + " ";
                  }
                  else
                  {
                      aParagraph = aParagraph + "\n";
                      break;
                  }
              }
              Console.WriteLine("Modified text:\n\n{0}", aParagraph);
          

          【讨论】:

            【解决方案7】:

            您可以使用StringReader 一次读取一行:

            using (StringReader reader = new StringReader(input))
            {
                string line = string.Empty;
                do
                {
                    line = reader.ReadLine();
                    if (line != null)
                    {
                        // do something with the line
                    }
            
                } while (line != null);
            }
            

            【讨论】:

            猜你喜欢
            • 2014-09-19
            • 2023-03-23
            • 2016-01-24
            • 1970-01-01
            • 2020-02-16
            • 1970-01-01
            • 2017-10-06
            • 1970-01-01
            相关资源
            最近更新 更多