如何在c#中替换字符串中的换行符?
当前回答
不要忘记replace不会在字符串中进行替换,而是返回一个替换了字符的新字符串。下面将删除换行符(而不是替换它们)。如果用其他方法替换它们,我将使用@Brian R. Bondy的方法,可能包装为扩展方法。记住,在调用Replace或提供的扩展方法之前,首先检查空值。
string line = ...
line = line.Replace( "\r", "").Replace( "\n", "" );
作为扩展方法:
public static class StringExtensions
{
public static string RemoveLineBreaks( this string lines )
{
return lines.Replace( "\r", "").Replace( "\n", "" );
}
public static string ReplaceLineBreaks( this string lines, string replacement )
{
return lines.Replace( "\r\n", replacement )
.Replace( "\r", replacement )
.Replace( "\n", replacement );
}
}
其他回答
我需要将\r\n替换为实际的回车和换行,并将\t替换为实际的制表符。所以我想到了以下几点:
public string Transform(string data)
{
string result = data;
char cr = (char)13;
char lf = (char)10;
char tab = (char)9;
result = result.Replace("\\r", cr.ToString());
result = result.Replace("\\n", lf.ToString());
result = result.Replace("\\t", tab.ToString());
return result;
}
将replace替换为Environment。换行符
myString = myString.Replace(System.Environment.NewLine, "replacement text"); //add a line terminating ;
正如在其他文章中提到的,如果字符串来自另一个环境(OS),那么您需要替换特定环境的新行控制字符实现。
为了确保所有可能的换行方式(Windows, Mac和Unix)都被替换,您应该使用:
string.Replace("\r\n", "\n").Replace('\r', '\n').Replace('\n', 'replacement');
按照这个顺序,当你发现一些行尾字符的组合时,不要使用额外的换行符。
我会使用环境。当我想为字符串插入换行符,而不是从字符串中删除所有换行符时,使用换行符。
根据不同的平台,你可以使用不同类型的换行符,但即使在同一个平台中,也经常使用不同类型的换行符。特别是在处理文件格式和协议时。
string ReplaceNewlines(string blockOfText, string replaceWith)
{
return blockOfText.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
}
使用。net 6中的new方法
myString = myString.ReplaceLineEndings();
替换当前字符串中的所有换行序列。
文档: ReplaceLineEndings
推荐文章
- 拒绝访问该路径
- 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扩展?