Easiest way to split a string on newlines in .NET?(在 .NET 中以换行符分割字符串的最简单方法?)
问题描述
我需要在 .NET 中将字符串拆分为换行符,而我知道拆分字符串的唯一方法是使用 拆分 方法.但是,这不允许我(轻松)在换行符上拆分,那么最好的方法是什么?
I need to split a string into newlines in .NET and the only way I know of to split strings is with the Split method. However that will not allow me to (easily) split on a newline, so what is the best way to do it?
推荐答案
要对字符串进行拆分,您需要使用带字符串数组的重载:
To split on a string you need to use the overload that takes an array of strings:
string[] lines = theText.Split(
new string[] { Environment.NewLine },
StringSplitOptions.None
);
如果要处理文本中不同类型的换行符,可以使用匹配多个字符串的功能.这将在任一类型的换行符上正确拆分,并在文本中保留空行和间距:
If you want to handle different types of line breaks in a text, you can use the ability to match more than one string. This will correctly split on either type of line break, and preserve empty lines and spacing in the text:
string[] lines = theText.Split(
new string[] { "
", "
", "
" },
StringSplitOptions.None
);
这篇关于在 .NET 中以换行符分割字符串的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 .NET 中以换行符分割字符串的最简单方法?


- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04