C#:通过多行字符串循环循环
答
我建议使用的StringReader
组合和我LineReader
类,这是部分的MiscUtil,但也可在this * answer - 你可以很容易地将该类复制到您自己的实用程序项目。你会使用这样的:
string text = @"First line
second line
third line";
foreach (string line in new LineReader(() => new StringReader(text)))
{
Console.WriteLine(line);
}
循环遍历字符串数据的身体所有行(不管是文件或其他)是很常见的,它不应该要求调用代码是用于测试空等:)说了这么多,如果你做想做一个手动循环,这是我通常更喜欢弗雷德里克的形式:
using (StringReader reader = new StringReader(input))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// Do something with the line
}
}
这种方式,你只需要测试无效一次,你不必考虑一个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);
}
答
从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 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 */ }
答
我知道这已经回答了,但我想补充我自己的答案:
using (var reader = new StringReader(multiLineString))
{
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
// Do something with the line
}
}