什麼是循環多行字符串的每一行而不使用更多內存的好方法(例如,不需要將其拆分成數組)?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循環