首页 > 解决方案 > C# StringReader.ReadLine() 可以在换行符处拆分字符串并保留空行吗?

问题描述

在 C# 应用程序中,我使用以下内容在换行符处拆分字符串。

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

但是,我想保留空行。例如,当我拆分以下源字符串时:

"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()跳过双换行符,结果只有 6 个子字符串。

/* 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."

我希望结果是 8 个子字符串,包括空行。

/* 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."

标签: c#stringsplitstringreader

解决方案


推荐阅读