Replace Line Breaks in a String C#

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

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

相关标签:
17条回答
  • 2020-11-22 11:33

    If your code is supposed to run in different environments, I would consider using the Environment.NewLine constant, since it is specifically the newline used in the specific environment.

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

    However, if you get the text from a file originating on another system, this might not be the correct answer, and you should replace with whatever newline constant is used on the other system. It will typically be \n or \r\n.

    0 讨论(0)
  • 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 );
       }
    }
    
    0 讨论(0)
  • 2020-11-22 11:42

    Why not both?

    string ReplacementString = "";
    
    Regex.Replace(strin.Replace(System.Environment.NewLine, ReplacementString), @"(\r\n?|\n)", ReplacementString);
    

    Note: Replace strin with the name of your input string.

    0 讨论(0)
  • 2020-11-22 11:43

    To make sure all possible ways of line breaks (Windows, Mac and Unix) are replaced you should use:

    string.Replace("\r\n", "\n").Replace('\r', '\n').Replace('\n', 'replacement');
    

    and in this order, to not to make extra line breaks, when you find some combination of line ending chars.

    0 讨论(0)
  • 2020-11-22 11:44

    To extend The.Anyi.9's answer, you should also be aware of the different types of line break in general use. Dependent on where your file originated, you may want to look at making sure you catch all the alternatives...

    string replaceWith = "";
    string removedBreaks = Line.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
    

    should get you going...

    0 讨论(0)
  • 2020-11-22 11:45

    Use the .Replace() method

    Line.Replace("\n", "whatever you want to replace with");
    
    0 讨论(0)
提交回复
热议问题