如何在c#中替换字符串中的换行符?


当前回答

我会使用环境。当我想为字符串插入换行符,而不是从字符串中删除所有换行符时,使用换行符。

根据不同的平台,你可以使用不同类型的换行符,但即使在同一个平台中,也经常使用不同类型的换行符。特别是在处理文件格式和协议时。

string ReplaceNewlines(string blockOfText, string replaceWith)
{
    return blockOfText.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
}

其他回答

使用.Replace()方法

Line.Replace("\n", "whatever you want to replace with");

我会使用环境。当我想为字符串插入换行符,而不是从字符串中删除所有换行符时,使用换行符。

根据不同的平台,你可以使用不同类型的换行符,但即使在同一个平台中,也经常使用不同类型的换行符。特别是在处理文件格式和协议时。

string ReplaceNewlines(string blockOfText, string replaceWith)
{
    return blockOfText.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
}

为了确保所有可能的换行方式(Windows, Mac和Unix)都被替换,您应该使用:

string.Replace("\r\n", "\n").Replace('\r', '\n').Replace('\n', 'replacement');

按照这个顺序,当你发现一些行尾字符的组合时,不要使用额外的换行符。

另一种选择是在有问题的字符串上创建一个StringReader。在读取器上,循环执行. readline()。然后你将直线分开,不管它们有什么(一致的或不一致的)分隔符。有了这些,你就可以随心所欲了;一种可能是使用StringBuilder并在其上调用. appendline。

这样做的好处是,可以让框架决定什么是“换行符”。

扩展The.Anyi。9的答案,你也应该知道一般使用的不同类型的换行符。根据文件的来源,您可能希望确保捕获所有替代选项…

string replaceWith = "";
string removedBreaks = Line.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);

应该能让你继续…