Replace Line Breaks in a String C#

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

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

17条回答
  •  说谎
    说谎 (楼主)
    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
      }
    }
    

提交回复
热议问题