如何在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);
推荐文章
- 拒绝访问该路径
- 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扩展?