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


当前回答

使用.Replace()方法

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

其他回答

为什么不是两者都有呢?

string ReplacementString = "";

Regex.Replace(strin.Replace(System.Environment.NewLine, ReplacementString), @"(\r\n?|\n)", ReplacementString);

注意:用输入字符串的名称替换string。

使用.Replace()方法

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

安全替换换行符的最好方法是

yourString.Replace("\r\n","\n") //handling windows linebreaks
.Replace("\r","\n")             //handling mac linebreaks

这将产生一个只有\n(如换行)作为换行符的字符串。 这段代码对于修复混合换行也很有用。

基于@mark-bayers的答案和更清晰的输出:

string result = Regex.Replace(ex.Message, @"(\r\n?|\r?\n)+", "replacement text");

它删除了\r\n, \n和\r,而偏爱较长的一个,并将多次出现简化为一次。

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

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

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