如何在c#中替换字符串中的换行符?


当前回答

如果您的代码应该在不同的环境中运行,我会考虑使用Environment。NewLine常量,因为它是特定环境中使用的换行符。

line = line.Replace(Environment.NewLine, "newLineReplacement");

但是,如果您从另一个系统上的文件中获取文本,这可能不是正确的答案,您应该替换为在另一个系统上使用的任何换行常数。它通常是\n或\r\n。

其他回答

将replace替换为Environment。换行符

myString = myString.Replace(System.Environment.NewLine, "replacement text"); //add a line terminating ;

正如在其他文章中提到的,如果字符串来自另一个环境(OS),那么您需要替换特定环境的新行控制字符实现。

string s = Regex.Replace(source_string, "\n", "\r\n");

or

string s = Regex.Replace(source_string, "\r\n", "\n");

这取决于你想走哪条路。

希望能有所帮助。

不要忘记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 );
   }
}
var answer = Regex.Replace(value, "(\n|\r)+", replacementString);

使用。net 6中的new方法

myString = myString.ReplaceLineEndings();

替换当前字符串中的所有换行序列。

文档: ReplaceLineEndings