Removing carriage return and new-line from the end of a string in c#

后端 未结 12 1080
终归单人心
终归单人心 2020-12-02 13:57

How do I remove the carriage return character (\\r) and the new line character(\\n) from the end of a string?

相关标签:
12条回答
  • 2020-12-02 14:35

    This should work ...

    var tst = "12345\n\n\r\n\r\r";
    var res = tst.TrimEnd( '\r', '\n' );
    
    0 讨论(0)
  • 2020-12-02 14:35
    String temp = s.Replace("\r\n","").Trim();
    

    s being the original string. (Note capitals)

    0 讨论(0)
  • 2020-12-02 14:37

    This was too easy -- for me I'm filtering out certain email items. I'm writing my own custom email junk filter. With \r and/or \n in the string it was wiping out all items instead of filtering.

    So, I just did filter = filter.Remove('\n') and filter = filter.Remove('\r'). I'm making my filter such that an end user can use Notepad to directly edit the file so there's no telling where these characters might embed themselves -- could be other than at the start or end of the string. So removing them all does it.

    The other entries all work but Remove might be the easiest?

    I learned quite a bit more about Regex from this post -- pretty cool work with its use here.

    0 讨论(0)
  • 2020-12-02 14:40
    varName.replace(/[\r\n]/mg, '')                                              
    
    0 讨论(0)
  • 2020-12-02 14:41

    For us VBers:

    TrimEnd(New Char() {ControlChars.Cr, ControlChars.Lf})
    
    0 讨论(0)
  • 2020-12-02 14:41
    string k = "This is my\r\nugly string. I want\r\nto change this. Please \r\n help!";
    k = System.Text.RegularExpressions.Regex.Replace(k, @"\r\n+", " ");
    
    0 讨论(0)
提交回复
热议问题