Replace Line Breaks in a String C#

后端 未结 17 1102
失恋的感觉
失恋的感觉 2020-11-22 11:16

How can I replace Line Breaks within a string in C#?

17条回答
  •  一生所求
    2020-11-22 11:35

    Don't forget that replace doesn't do the replacement in the string, but returns a new string with the characters replaced. The following will remove line breaks (not replace them). I'd use @Brian R. Bondy's method if replacing them with something else, perhaps wrapped as an extension method. Remember to check for null values first before calling Replace or the extension methods provided.

    string line = ...
    
    line = line.Replace( "\r", "").Replace( "\n", "" );
    

    As extension methods:

    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 );
       }
    }
    

提交回复
热议问题