Warm tip: This article is reproduced from serverfault.com, please click

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

(loops - C#: Looping through lines of multiline string)

发布于 2009-09-30 19:31:18

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

Questioner
flamey
Viewed
0
2017-05-23 19:47:15

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