什么是循环多行字符串的每一行而不使用更多内存的好方法(例如,不需要将其拆分成数组)?C#:通过多行字符串循环循环
66
A
回答
116
我建议使用的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);
}
循环遍历字符串数据的身体所有行(不管是文件或其他)是很常见的,它不应该要求调用代码是用于测试空等:)说了这么多,如果你做想做一个手动循环,这是我通常更喜欢弗雷德里克的形式:
using (StringReader reader = new StringReader(input))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// Do something with the line
}
}
这种方式,你只需要测试无效一次,你不必考虑一个do/while循环(由于某种原因,它总是需要我花更多的努力来阅读,而不是直接的while循环)。
53
您可以使用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);
}
5
从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);
1
下面是一个简单的代码片段,会发现在字符串中的第一个非空行:
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 */ }
0
我知道这已经回答了,但我想补充我自己的答案:
using (var reader = new StringReader(multiLineString))
{
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
// Do something with the line
}
}
相关问题
- 1. C++通过字符串循环
- 2. C#:循环通过在字符串
- 3. Java - 通过字符串数组进行循环循环
- 4. 在ReactJs中,通过循环字符串
- 5. Grepl in for循环,通过字符串
- 6. 循环回通过字符串数组
- 7. 通过循环连接字符串
- 8. VIM:通过字符串循环
- 9. 通过很多行循环
- 10. 通过字符数组和循环字符循环
- 11. 通过循环
- 12. C#循环通过关键
- 13. C#循环通过子类
- 14. 循环通过多阵列
- 15. 多后Vlaue通过循环
- 16. 通过多个datagridview循环
- 17. 字符串循环问题
- 18. 双字符串Java循环
- 19. 循环虽然字符串
- 20. 循环字符串创建
- 21. for循环中的C++字符串
- 22. C++ while循环和字符串长度
- 23. C#在循环中操纵字符串
- 24. 在r中循环多个字符串
- 25. 多个字符串解析循环
- 26. 通过字符串汇编循环来计算字符数
- 27. 循环通过行动
- 28. $ .each()循环通过json不循环
- 29. 通过Json循环的foreach循环
- 30. 通过Arrayyl循环java循环