2009-09-30 134 views

回答

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