How can I remove “\r\n” from a string in C#? Can I use a regular expression?

前端 未结 8 1655
粉色の甜心
粉色の甜心 2020-12-04 23:16

I am trying to persist string from an ASP.NET textarea. I need to strip out the carriage return line feeds and then break up whatever is left into a string array of 50 chara

8条回答
  •  北海茫月
    2020-12-05 00:00

    Here is the perfect method:

    Please note that Environment.NewLine works on on Microsoft platforms.

    In addition to the above, you need to add \r and \n in a separate function!

    Here is the code which will support whether you type on Linux, Windows, or Mac:

    var stringTest = "\r Test\nThe Quick\r\n brown fox";
    
    Console.WriteLine("Original is:");
    Console.WriteLine(stringTest);
    Console.WriteLine("-------------");
    
    stringTest = stringTest.Trim().Replace("\r", string.Empty);
    stringTest = stringTest.Trim().Replace("\n", string.Empty);
    stringTest = stringTest.Replace(Environment.NewLine, string.Empty);
    
    Console.WriteLine("Output is : ");
    Console.WriteLine(stringTest);
    Console.ReadLine();
    

提交回复
热议问题