在不使用更多内存的情况下循环多行字符串的每一行的好方法是什么(例如,不将其拆分成数组)?
发布于 2009-09-30 19:41:01
我建议结合使用StringReader和我的LineReader类,它是MiscUtil的一部分,但也可以在this StackOverflow answer中使用-您可以很容易地将该类复制到您自己的实用程序项目中。你可以这样使用它:
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-30 19:36:37
您可以使用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);
}发布于 2017-02-06 16:57:49
我知道这个问题已经得到了回答,但我想补充我自己的答案:
using (var reader = new StringReader(multiLineString))
{
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
// Do something with the line
}
}https://stackoverflow.com/questions/1500194
复制相似问题