Can C# StringReader.ReadLine() split a string on line breaks and keep empty lines?

295 Views Asked by At

In a C# application, I use the following to split a string on the line breaks.

using System;
using System.Collections.Generic;
using System.IO;

public static class StringUtil
{
  public static IEnumerable<string> splitByLines( this string src )
  {
    if ( src == null )
    {
      yield break;
    }

    using ( StringReader reader = new StringReader( src ) )
    {
      string line;
      while ( ( line = reader.ReadLine() ) != null )
      {
        yield return line;
      }
    }
  }
}

However, I want to keep empty lines. For example, when I split the following source string:

"Now is the time for all good men\r\nto come to the aid\r\nof their country.\r\n\r\nTo err is human,\r\nto really foul things up requires a computer.\r\n\r\nAble was I ere I saw Elba."

StringReader.ReadLine() skips over the double line breaks, and the result is just 6 substrings.

/* Undesirable result.  Empty lines are absent. */
"Now is the time for all good men"
"to come to the aid"
"of their country."
"To err is human,"
"to really foul things up requires a computer."
"Able was I ere I saw Elba."

I want the result to be 8 substrings, including the empty lines.

/* Desirable result.  Empty lines are kept. */
"Now is the time for all good men"
"to come to the aid"
"of their country."
""
"To err is human,"
"to really foul things up requires a computer."
""
"Able was I ere I saw Elba."
0

There are 0 best solutions below