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


当前回答

将replace替换为Environment。换行符

myString = myString.Replace(System.Environment.NewLine, "replacement text"); //add a line terminating ;

正如在其他文章中提到的,如果字符串来自另一个环境(OS),那么您需要替换特定环境的新行控制字符实现。

其他回答

使用.Replace()方法

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

这是一个非常冗长的单行解决方案,但它是我发现的唯一一个工作,如果你不能使用特殊字符转义,如“\r”和“\n”和\x0d和\u000D以及System.Environment.NewLine作为参数的replace()方法

MyStr.replace(  System.String.Concat( System.Char.ConvertFromUtf32(13).ToString(), System.Char.ConvertFromUtf32(10).ToString() ), ReplacementString  );

这有点离题了,但是为了让它在Visual Studio的XML .props文件中工作,这些文件通过XML属性调用. net,我必须像下面所示那样对它进行修饰。 Visual Studio XML—> . net环境只是不接受特殊字符转义,如“\r”和“\n”以及\x0d和\u000D以及System.Environment.NewLine作为replace()方法的参数。

$([System.IO.File]::ReadAllText('MyFile.txt').replace( $([System.String]::Concat($([System.Char]::ConvertFromUtf32(13).ToString()),$([System.Char]::ConvertFromUtf32(10).ToString()))),$([System.String]::Concat('^',$([System.Char]::ConvertFromUtf32(13).ToString()),$([System.Char]::ConvertFromUtf32(10).ToString())))))

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

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

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

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

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

使用。net 6中的new方法

myString = myString.ReplaceLineEndings();

替换当前字符串中的所有换行序列。

文档: ReplaceLineEndings