110

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

4

7 回答 7

170

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

string text = @"First line
second line
third line";

foreach (string line in new LineReader(() => new StringReader(text)))
{
    Console.WriteLine(line);
}

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

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

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

于 2009-09-30T19:41:00.833 回答
82

您可以使用 a 一次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);
}
于 2009-09-30T19:36:36.770 回答
15

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

using (var reader = new StringReader(multiLineString))
{
    for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
    {
        // Do something with the line
    }
}
于 2017-02-06T08:57:48.927 回答
7

来自 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);
于 2009-09-30T19:37:04.967 回答
2

这是一个快速代码片段,它将在字符串中找到第一个非空行:

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 */ }
于 2010-10-11T22:06:32.577 回答
1

尝试使用 String.Split 方法:

string text = @"First line
second line
third line";

foreach (string line in text.Split('\n'))
{
    // do something
}
于 2020-07-03T08:31:40.237 回答
0

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

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

using (var stringReader = new StringReader(input))
{
    var line = await stringReader.ReadLineAsync();

    while (line != null)
    {
        // do something
        line = await stringReader.ReadLineAsync();
    }
}

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

于 2020-11-28T12:08:50.410 回答