Replace Line Breaks in a String C#

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

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

17条回答
  •  天命终不由人
    2020-11-22 11:31

    If you want to replace only the newlines:

    var input = @"sdfhlu \r\n sdkuidfs\r\ndfgdgfd";
    var match = @"[\\ ]+";
    var replaceWith = " ";
    Console.WriteLine("input: " + input);
    var x = Regex.Replace(input.Replace(@"\n", replaceWith).Replace(@"\r", replaceWith), match, replaceWith);
    Console.WriteLine("output: " + x);
    

    If you want to replace newlines, tabs and white spaces:

    var input = @"sdfhlusdkuidfs\r\ndfgdgfd";
    var match = @"[\\s]+";
    var replaceWith = "";
    Console.WriteLine("input: " + input);
    var x = Regex.Replace(input, match, replaceWith);
    Console.WriteLine("output: " + x);
    

提交回复
热议问题