如何在c#中替换字符串中的换行符?
当前回答
使用.Replace()方法
Line.Replace("\n", "whatever you want to replace with");
其他回答
为什么不是两者都有呢?
string ReplacementString = "";
Regex.Replace(strin.Replace(System.Environment.NewLine, ReplacementString), @"(\r\n?|\n)", ReplacementString);
注意:用输入字符串的名称替换string。
使用.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(如换行)作为换行符的字符串。 这段代码对于修复混合换行也很有用。
基于@mark-bayers的答案和更清晰的输出:
string result = Regex.Replace(ex.Message, @"(\r\n?|\r?\n)+", "replacement text");
它删除了\r\n, \n和\r,而偏爱较长的一个,并将多次出现简化为一次。
我会使用环境。当我想为字符串插入换行符,而不是从字符串中删除所有换行符时,使用换行符。
根据不同的平台,你可以使用不同类型的换行符,但即使在同一个平台中,也经常使用不同类型的换行符。特别是在处理文件格式和协议时。
string ReplaceNewlines(string blockOfText, string replaceWith)
{
return blockOfText.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
}
推荐文章
- 拒绝访问该路径
- 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扩展?