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


当前回答

这是一个非常冗长的单行解决方案,但它是我发现的唯一一个工作,如果你不能使用特殊字符转义,如“\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())))))

其他回答

var answer = Regex.Replace(value, "(\n|\r)+", replacementString);

如果你只想替换换行符:

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

使用.Replace()方法

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

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

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

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

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

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