问题描述
我需要在 .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 中以换行符分割字符串的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!