C#:循环遍历多行字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1500194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:11:46  来源:igfitidea点击:

C#: Looping through lines of multiline string

c#loopsmultilinestring

提问by flamey

What is a good way to loop through each line of a multiline string without using much more memory (for example without splitting it into an array)?

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

采纳答案by Jon Skeet

I suggest using a combination of StringReaderand my LineReaderclass, which is part of MiscUtilbut also available in this StackOverflow answer- you can easily copy just that class into your own utility project. You'd use it like this:

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

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

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

Looping over all the lines in a body of string data (whether that's a file or whatever) is so common that it shouldn't require the calling code to be testing for null etc :) Having said that, if you dowant to do a manual loop, this is the form that I typically prefer over Fredrik's:

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

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

This way you only have to test for nullity once, and you don't have to think about a do/while loop either (which for some reason always takes me more effort to read than a straight while loop).

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

回答by Fredrik M?rk

You can use a StringReaderto read a line at a time:

您可以使用 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);
}

回答by tster

from MSDN for StringReader

来自 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);

回答by palswim

Here's a quick code snippet that will find the first non-empty line in a string:

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

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 */ }

回答by Niels

I know this has been answered, but I'd like to add my own answer:

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

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

回答by NickG

To update this ancient question for .NET 4, there is now a much neater way:

为了更新 .NET 4 这个古老的问题,现在有一个更简洁的方法:

var lines = File.ReadAllLines(filename);

foreach (string line in lines)
{
    Console.WriteLine(line);
}