c# - 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."
解决方案
推荐阅读
- python - 为什么我不能使用队列显示返回的图像
- electron - 生产模式下的文件路径
- docker - 如何在 docker 的 jenkins 中调用 yarn 命令?
- php - Wordpress - 将项目上传到服务器后斜杠消失
- alexa - 无法从开发者控制台测试 alexa 技能
- node.js - Google Sheets API -- 自动获取最大工作表范围
- java - 用 Java 打开终端并执行“java -jar”
- html - Non Responsive Webpage (Mobile)
- c# - 在 C# 中将字符串类型日期值从 'dd/mm/yyyy hh:mm:ss' 解析为 'mm/dd/yyyy hh:mm:ss' 时出现奇怪的错误
- python - Building a histogram from an array with: np.histogram