C#:循环多行字符串

fla*_*mey 87 c# loops multilinestring

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

Jon*_*eet 144

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

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

foreach (string line in new LineReader(() => new StringReader(text)))
{
    Console.WriteLine(line);
}
Run Code Online (Sandbox Code Playgroud)

循环遍历字符串数据的身体所有行(不管是文件或其他)是很常见的,它不应该要求调用代码是这样说的测试等空:),如果你想做一个手动循环,这是我通常比Fredrik更喜欢的形式:

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

这样你只需要测试一次null值,你也不必考虑do/while循环(由于某种原因,它总是比直接循环需要更多努力才能读取).


Fre*_*örk 70

您可以使用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);
}
Run Code Online (Sandbox Code Playgroud)

  • 伟大的; +1;这有帮助;但我只是想补充一点,实际上并不需要使用“using”块,因为在这种情况下没有任何资源可以关闭。请参阅[docs.microsoft.com 上的 StringReader 文章中的备注](https://docs.microsoft.com/en-us/dotnet/api/system.io.stringreader?view=netcore-3.1#remarks) (2认同)

tst*_*ter 7

来自MSDN for 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);
Run Code Online (Sandbox Code Playgroud)


小智 7

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

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