如何循环遍历多行字符串中的每一行,而不使用更多内存(例如不将其拆分为数组)?
我建议使用StringReader
和我的LineReader
类的组合,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
}
}
这样您只需测试一次是否为 null,而且也不必考虑 do/while 循环(相比起直接的 while 循环,读起来总是需要更多的精力)。
您可以使用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);
}
我知道这个问题已经有答案了,但是我想加上我的答案:
using (var reader = new StringReader(multiLineString))
{
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
// Do something with the line
}
}
from 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);
string text = @"First line
second line
third line";
foreach (string line in text.Split('\n'))
{
// do something
}
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 */ }
ReadLine
。using (var stringReader = new StringReader(input))
{
var line = await stringReader.ReadLineAsync();
while (line != null)
{
// do something
line = await stringReader.ReadLineAsync();
}
}
我知道这可能被认为不符合DRY原则,但考虑到它的简单性,我认为值得考虑。
public static IEnumerable<string> EnumerateLines(this string source)
{
ArgumentNullException.ThrowIfNull(source);
using StringReader reader = new StringReader(source);
while(reader.ReadLine() is { } line)
{
yield return line;
}
}