如何在c#中替换字符串中的换行符?
当前回答
string s = Regex.Replace(source_string, "\n", "\r\n");
or
string s = Regex.Replace(source_string, "\r\n", "\n");
这取决于你想走哪条路。
希望能有所帮助。
其他回答
使用.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,而偏爱较长的一个,并将多次出现简化为一次。
我会使用环境。当我想为字符串插入换行符,而不是从字符串中删除所有换行符时,使用换行符。
根据不同的平台,你可以使用不同类型的换行符,但即使在同一个平台中,也经常使用不同类型的换行符。特别是在处理文件格式和协议时。
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
扩展The.Anyi。9的答案,你也应该知道一般使用的不同类型的换行符。根据文件的来源,您可能希望确保捕获所有替代选项…
string replaceWith = "";
string removedBreaks = Line.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
应该能让你继续…
推荐文章
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 将整数转换为字符串,以逗号表示千
- 转换为值类型'Int32'失败,因为物化值为空
- 将JavaScript字符串中的多个空格替换为单个空格
- c#中有任何连接字符串解析器吗?
- printf()和puts()在C语言中的区别是什么?
- 在Linq中转换int到字符串到实体的问题
- 是否可以动态编译和执行c#代码片段?
- 创建自定义MSBuild任务时,如何从c#代码获取当前项目目录?
- MSBuild路径
- c#和Java的主要区别是什么?
- 在c#中创建一个特定时区的DateTime
- .NET中的属性是什么?
- csproj文件中的“Service Include”是干什么用的?