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


当前回答

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

将replace替换为Environment。换行符

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

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

如果你只想替换换行符:

var input = @"sdfhlu \r\n sdkuidfs\r\ndfgdgfd";
var match = @"[\\ ]+";
var replaceWith = " ";
Console.WriteLine("input: " + input);
var x = Regex.Replace(input.Replace(@"\n", replaceWith).Replace(@"\r", replaceWith), match, replaceWith);
Console.WriteLine("output: " + x);

如果你想替换换行符,制表符和空格:

var input = @"sdfhlusdkuidfs\r\ndfgdgfd";
var match = @"[\\s]+";
var replaceWith = "";
Console.WriteLine("input: " + input);
var x = Regex.Replace(input, match, replaceWith);
Console.WriteLine("output: " + x);

到目前为止发布的解决方案要么只替代Environment。如果替换字符串包含换行符,则会失败,因为它们调用string。多次替换。

下面是一个解决方案,它使用正则表达式在一次字符串传递中完成所有三个替换。这意味着替换字符串可以安全地包含换行符。

string result = Regex.Replace(input, @"\r\n?|\n", replacementString);