Answers:
我建议使用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循环相比,读取它总是要花更多的精力)。
您可以一次使用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);
}
从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);
尝试使用String.Split方法:
string text = @"First line
second line
third line";
foreach (string line in text.Split('\n'))
{
// do something
}