C#:遍历多行字符串的行


100

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

Answers:


158

我建议使用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循环相比,读取它总是要花更多的精力)。


74

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

1
大; +1; 这有所帮助;但我只是想补充一点,实际上并不需要使用“ using”块,因为在这种情况下没有任何资源可以关闭。请参阅docs.microsoft.com上StringReader文章中的说明
RD Alkire

10

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

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

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

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

2

要更新.NET 4的这一古老问题,现在有一种更整洁的方法:

var lines = File.ReadAllLines(filename);

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

0

尝试使用String.Split方法:

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

foreach (string line in text.Split('\n'))
{
    // do something
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.