我需要在.NET中将字符串拆分为换行符,我知道拆分字符串的唯一方法是使用Split方法。 但是,这不允许我(轻松)拆分换行符,那么最好的方法是什么?
#1楼
对于字符串变量s :
s.Split(new string[]{Environment.NewLine},StringSplitOptions.None)
这使用了您的环境对行结尾的定义。 在Windows上,行结尾是CR-LF(回车,换行)或C#的转义字符\\r\\n 。
这是一个可靠的解决方案,因为如果你用String.Join重新组合这些行,这等于你的原始字符串:
var lines = s.Split(new string[]{Environment.NewLine},StringSplitOptions.None);
var reconstituted = String.Join(Environment.NewLine,lines);
Debug.Assert(s==reconstituted);
什么不该做:
拆分分隔符new char[]{Environment.NewLine} ,因为在Windows上,这将为每个新行创建一个空字符串元素。
#2楼
愚蠢的回答:写一个临时文件,这样你就可以使用古老的File.ReadLines
var s = "Hello\r\nWorld";
var path = Path.GetTempFileName();
using (var writer = new StreamWriter(path))
{
writer.Write(s);
}
var lines = File.ReadLines(path);
#3楼
using (System.IO.StringReader reader = new System.IO.StringReader(input)) {
string line = reader.ReadLine();
}
#4楼
正则表达式也是一个选项:
private string[] SplitStringByLineFeed(string inpString)
{
string[] locResult = Regex.Split(inpString, "[\r\n]+");
return locResult;
}
#5楼
要拆分字符串,您需要使用带有字符串数组的重载:
string[] lines = theText.Split(
new[] { Environment.NewLine },
StringSplitOptions.None
);
编辑:
如果要在文本中处理不同类型的换行符,可以使用匹配多个字符串的功能。 这将在任何类型的换行符上正确分割,并在文本中保留空行和间距:
string[] lines = theText.Split(
new[] { "\r\n", "\r", "\n" },
StringSplitOptions.None
);