如何在 C# 中替换字符串中的换行符?
使用 Environment.NewLine
替换
myString = myString.Replace(System.Environment.NewLine, "replacement text"); //add a line terminating ;
如其他帖子中所述,如果字符串来自另一个环境 (OS),那么您需要替换 new line control characters 的特定环境实现。
到目前为止发布的解决方案要么仅替换 Environment.NewLine
,要么在替换字符串包含换行符时失败,因为它们多次调用 string.Replace
。
这是一个使用正则表达式的解决方案,只需一次遍历字符串即可完成所有三个替换。这意味着替换字符串可以安全地包含换行符。
string result = Regex.Replace(input, @"\r\n?|\n", replacementString);
要扩展 The.Anyi.9 的答案,您还应该注意 different types of line break in general use。根据您的文件的来源,您可能需要查看确保您抓住所有替代方案......
string replaceWith = "";
string removedBreaks = Line.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
应该让你去...
Line.Replace("\n", replaceWith).Replace("\r", replaceWith);
还不够吗?
\r\n
,您最终会得到两次替换字符串 - 不理想。
当我想为字符串插入换行符时,我会使用 Environment.Newline,但不想从字符串中删除所有换行符。
根据您的平台,您可以有不同类型的换行符,但即使在同一个平台内,也经常使用不同类型的换行符。特别是在处理文件格式和协议时。
string ReplaceNewlines(string blockOfText, string replaceWith)
{
return blockOfText.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
}
如果您的代码应该在不同的环境中运行,我会考虑使用 Environment.NewLine
常量,因为它专门用于特定环境中的 newline
。
line = line.Replace(Environment.NewLine, "newLineReplacement");
但是,如果您从源自另一个系统的文件中获取文本,这可能不是正确的答案,您应该替换为其他系统上使用的任何换行符常量。它通常是 \n
或 \r\n
。
如果您想“清理”新行,使用正则表达式 @"[\r\n]+"
的火焰波特注释是最佳选择。
using System;
using System.Text.RegularExpressions;
class MainClass {
public static void Main (string[] args) {
string str = "AAA\r\nBBB\r\n\r\n\r\nCCC\r\r\rDDD\n\n\nEEE";
Console.WriteLine (str.Replace(System.Environment.NewLine, "-"));
/* Result:
AAA
-BBB
-
-
-CCC
DDD---EEE
*/
Console.WriteLine (Regex.Replace(str, @"\r\n?|\n", "-"));
// Result:
// AAA-BBB---CCC---DDD---EEE
Console.WriteLine (Regex.Replace(str, @"[\r\n]+", "-"));
// Result:
// AAA-BBB-CCC-DDD-EEE
}
}
不要忘记 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 );
}
}
''
- 没有空字符之类的东西。 '\0'
会起作用吗?
string.Empty
更好,请务必使用它。
为了确保所有可能的换行方式(Windows、Mac 和 Unix)都被替换,你应该使用:
string.Replace("\r\n", "\n").Replace('\r', '\n').Replace('\n', 'replacement');
并按此顺序,当您找到一些行尾字符组合时,不要进行额外的换行符。
为什么不兼得?
string ReplacementString = "";
Regex.Replace(strin.Replace(System.Environment.NewLine, ReplacementString), @"(\r\n?|\n)", ReplacementString);
注意:将 strin
替换为您的输入字符串的名称。
在 .NET 6 中使用新方法
myString = myString.ReplaceLineEndings("");
我需要将 \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;
}
var answer = Regex.Replace(value, "(\n|\r)+", replacementString);
由于新行可以由 \n
、\r
和 \r\n
分隔,我们首先将 \r
和 \r\n
替换为 \n
,然后才拆分数据字符串。
以下行应转到 parseCSV
方法:
function parseCSV(data) {
//alert(data);
//replace UNIX new lines
data = data.replace(/\r\n/g, "\n");
//replace MAC new lines
data = data.replace(/\r/g, "\n");
//split into rows
var rows = data.split("\n");
}
使用 .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 (例如换行符)作为换行符的字符串。此代码对于修复混合换行符也很有用。
另一种选择是在有问题的字符串上创建一个 StringReader
。在阅读器上,循环执行 .ReadLine()
。然后你有分隔线,不管他们有什么(一致或不一致)分隔符。有了它,您可以随心所欲地进行;一种可能性是使用 StringBuilder
并在其上调用 .AppendLine
。
优点是,您让框架决定什么构成“换行符”。
string s = Regex.Replace(source_string, "\n", "\r\n");
或者
string s = Regex.Replace(source_string, "\r\n", "\n");
取决于你想走哪条路。
希望它有所帮助。
如果您只想替换换行符:
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);
基于@mark-bayers 的回答和更清晰的输出:
string result = Regex.Replace(ex.Message, @"(\r\n?|\r?\n)+", "replacement text");
它删除了 \r\n
、 \n
和 \r
,同时更喜欢更长的一个并将多次出现简化为一个。
不定期副业成功案例分享