C#:循环多行string的行

什么是一个很好的方式来循环多行string的每一行,而不使用更多的内存(例如没有将其分割成数组)?

我build议使用StringReader和我的LineReader类的组合,这是MiscUtil的一部分,但也可以在这个StackOverflow的答案 – 你可以很容易地将该类复制到自己的实用工程。 你会这样使用它:

 string text = @"First line second line third line"; foreach (string line in new LineReader(() => new StringReader(text))) { Console.WriteLine(line); } 

循环遍历string数据体中的所有行(无论是文件还是其他types)非常常见,不需要调用代码来testingnull等:)如果您想要做一个手动循环,这是我通常比Fredrik更喜欢的forms:

 using (StringReader reader = new StringReader(input)) { string line; while ((line = reader.ReadLine()) != null) { // Do something with the line } } 

这样你只需要一次testing无效性,而且不必考虑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中的第一个非空行:

 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 } }