问题描述
如何将多行字符串拆分成行?
How do you split multi-line string into lines?
我知道这样
var result = input.Split("
".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
看起来有点难看并且丢失了空行.有没有更好的解决方案?
looks a bit ugly and loses empty lines. Is there a better solution?
推荐答案
如果它看起来很丑,只需删除不必要的
ToCharArray
调用.如果您想按
或
进行拆分,您有两个选择:
If you want to split by either
or
, you've got two options:
使用数组字面量 - 但这将为 Windows 样式的行结尾提供空行:
Use an array literal – but this will give you empty lines for Windows-style line endings
:
var result = text.Split(new [] { ' ', ' ' });
使用正则表达式,如 Bart 所示:
Use a regular expression, as indicated by Bart:
var result = Regex.Split(text, " | | ");
如果要保留空行,为什么要明确告诉 C# 将它们丢弃?(StringSplitOptions
参数) – 使用 StringSplitOptions.None
代替.
If you want to preserve empty lines, why do you explicitly tell C# to throw them away? (StringSplitOptions
parameter) – use StringSplitOptions.None
instead.
这篇关于将字符串拆分为行的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!