如何在c#中替换字符串中的换行符?
当前回答
为什么不是两者都有呢?
string ReplacementString = "";
Regex.Replace(strin.Replace(System.Environment.NewLine, ReplacementString), @"(\r\n?|\n)", ReplacementString);
注意:用输入字符串的名称替换string。
其他回答
如果您的代码应该在不同的环境中运行,我会考虑使用Environment。NewLine常量,因为它是特定环境中使用的换行符。
line = line.Replace(Environment.NewLine, "newLineReplacement");
但是,如果您从另一个系统上的文件中获取文本,这可能不是正确的答案,您应该替换为在另一个系统上使用的任何换行常数。它通常是\n或\r\n。
这是一个非常冗长的单行解决方案,但它是我发现的唯一一个工作,如果你不能使用特殊字符转义,如“\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())))))
使用.Replace()方法
Line.Replace("\n", "whatever you want to replace with");
基于@mark-bayers的答案和更清晰的输出:
string result = Regex.Replace(ex.Message, @"(\r\n?|\r?\n)+", "replacement text");
它删除了\r\n, \n和\r,而偏爱较长的一个,并将多次出现简化为一次。
将replace替换为Environment。换行符
myString = myString.Replace(System.Environment.NewLine, "replacement text"); //add a line terminating ;
正如在其他文章中提到的,如果字符串来自另一个环境(OS),那么您需要替换特定环境的新行控制字符实现。
推荐文章
- 拒绝访问该路径
- Visual Studio - Resx文件默认“内部”为“公共”
- 使用linq转换列表到字典,不用担心重复
- 单元测试:日期时间。现在
- 什么是回调?
- .NET中的KeyDown和KeyPress有什么区别?
- 返回匿名类型的结果?
- 你能解释一下流的概念吗?
- indexOf()和search()的区别是什么?
- 何时使用IList,何时使用List
- ConfigurationManager。AppSettings在.NET Core 2.0中可用?
- 我如何在Swift连接字符串?
- 在c#的控制台应用程序中使用'async
- 在单元测试中设置HttpContext.Current.Session
- 如何开始开发Internet Explorer扩展?