我该如何在C#中替换字符串中的换行符?
使用 Environment.NewLine
替换字符串中的换行符。
myString = myString.Replace(System.Environment.NewLine, "replacement text"); //add a line terminating ;
如其他帖子所述,如果该字符串来自于另一个环境(操作系统),那么您需要替换该特定环境中的换行控制字符的实现。
<span style="white-space: pre-line">@Model.CommentText</span>
- Mike OlundEnvironment.NewLine
,要么如果替换字符串包含换行符,则会因调用多次string.Replace
而失败。string result = Regex.Replace(input, @"\r\n?|\n", replacementString);
string replaceWith = "";
string removedBreaks = Line.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
应该让你开始...
Line.Replace("\n", replaceWith).Replace("\r", replaceWith);
这个不够吗? - Thomas Ayoub\r\n
的话,最终会得到两次替换字符串,这并不理想。 - ZombieSheep如果我想要在字符串中插入一个换行符但不删除所有的换行符,我会使用Environment.Newline。
根据您的平台,您可以有不同类型的换行符,但即使在同一平台上,通常也会使用不同类型的换行符。特别是当处理文件格式和协议时。
string ReplaceNewlines(string blockOfText, string replaceWith)
{
return blockOfText.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
}
Environment.NewLine
替换换行符 - 有时这可能是需要的 :) - Nicolai Krüger如果你想要“清除”新行,使用正则表达式 @"[\r\n]+"
来评论 Flamebaud 是最好的选择。
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
}
}
如果你的代码需要在不同环境中运行,建议使用Environment.NewLine
常量,因为它是特定环境中使用的换行符
。
line = line.Replace(Environment.NewLine, "newLineReplacement");
然而,如果你从另一个系统的文件中获取文本,则可能不是正确的答案,你应该替换为在其他系统上使用的任何换行符常量。通常会是\n
或 \r\n
。
为了确保替换所有可能的换行方式(Windows、Mac 和 Unix),您应该使用:
string.Replace("\r\n", "\n").Replace('\r', '\n').Replace('\n', 'replacement');
按照这个顺序,当你发现某些行末字符的组合时,不要产生额外的换行。
不要忘记,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'
代替? - Shevekstring.Empty
更好,请放心使用。 - tvanfosson为什么不两者兼顾呢?
string ReplacementString = "";
Regex.Replace(strin.Replace(System.Environment.NewLine, ReplacementString), @"(\r\n?|\n)", ReplacementString);
注意:请将strin
替换为您输入字符串的名称。