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


当前回答

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

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

应该能让你继续…

其他回答

将replace替换为Environment。换行符

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

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

string s = Regex.Replace(source_string, "\n", "\r\n");

or

string s = Regex.Replace(source_string, "\r\n", "\n");

这取决于你想走哪条路。

希望能有所帮助。

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

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

应该能让你继续…

使用。net 6中的new方法

myString = myString.ReplaceLineEndings();

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

文档: ReplaceLineEndings

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

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

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