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


当前回答

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

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

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

其他回答

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

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

应该能让你继续…

如果您的代码应该在不同的环境中运行,我会考虑使用Environment。NewLine常量,因为它是特定环境中使用的换行符。

line = line.Replace(Environment.NewLine, "newLineReplacement");

但是,如果您从另一个系统上的文件中获取文本,这可能不是正确的答案,您应该替换为在另一个系统上使用的任何换行常数。它通常是\n或\r\n。

使用.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(如换行)作为换行符的字符串。 这段代码对于修复混合换行也很有用。

如果你只想替换换行符:

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);