Replace Line Breaks in a String C#

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

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

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

    The solutions posted so far either only replace Environment.NewLine or they fail if the replacement string contains line breaks because they call string.Replace multiple times.

    Here's a solution that uses a regular expression to make all three replacements in just one pass over the string. This means that the replacement string can safely contain line breaks.

    string result = Regex.Replace(input, @"\r\n?|\n", replacementString);
    
    0 讨论(0)
  • 2020-11-22 11:53

    Use replace with Environment.NewLine

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

    As mentioned in other posts, if the string comes from another environment (OS) then you'd need to replace that particular environments implementation of new line control characters.

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

    As new line can be delimited by \n, \r and \r\n, first we’ll replace \r and \r\n with \n, and only then split data string.

    The following lines should go to the parseCSV method:

    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");
    }
    
    0 讨论(0)
  • 2020-11-22 11:53
    string s = Regex.Replace(source_string, "\n", "\r\n");
    

    or

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

    depending on which way you want to go.

    Hopes it helps.

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

    if you want to "clean" the new lines, flamebaud comment using regex @"[\r\n]+" is the best choice.

    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
      }
    }
    
    0 讨论(0)
提交回复
热议问题