How to remove new line characters from a string?

后端 未结 11 915
时光取名叫无心
时光取名叫无心 2020-11-27 10:32

I have a string in the following format

string s = \"This is a Test String.\\n   This is a next line.\\t This is a tab.\\n\'

I want to remo

相关标签:
11条回答
  • 2020-11-27 11:02

    You want to use String.Replace to remove a character.

    s = s.Replace("\n", String.Empty);
    s = s.Replace("\r", String.Empty);
    s = s.Replace("\t", String.Empty);
    

    Note that String.Trim(params char[] trimChars) only removes leading and trailing characters in trimChars from the instance invoked on.

    You could make an extension method, which avoids the performance problems of the above of making lots of temporary strings:

    static string RemoveChars(this string s, params char[] removeChars) {
        Contract.Requires<ArgumentNullException>(s != null);
        Contract.Requires<ArgumentNullException>(removeChars != null);
        var sb = new StringBuilder(s.Length);
        foreach(char c in s) { 
            if(!removeChars.Contains(c)) {
                sb.Append(c);
            }
        }
        return sb.ToString();
    }
    
    0 讨论(0)
  • 2020-11-27 11:03

    You can use Trim if you want to remove from start and end.

    string stringWithoutNewLine = "\n\nHello\n\n".Trim();
    
    0 讨论(0)
  • 2020-11-27 11:08

    just do that

    s = s.Replace("\n", String.Empty).Replace("\t", String.Empty).Replace("\r", String.Empty);
    
    0 讨论(0)
  • 2020-11-27 11:17

    FYI,

    Trim() does that already.

    The following LINQPad sample:

    void Main()
    {
        var s = " \rsdsdsdsd\nsadasdasd\r\n ";
        s.Length.Dump();
        s.Trim().Length.Dump();
    }
    

    Outputs:

    23
    18
    
    0 讨论(0)
  • 2020-11-27 11:20

    If speed and low memory usage are important, do something like this:

    var sb = new StringBuilder(s.Length);
    
    foreach (char i in s)
        if (i != '\n' && i != '\r' && i != '\t')
            sb.Append(i);
    
    s = sb.ToString();
    
    0 讨论(0)
  • 2020-11-27 11:23

    I know this is an old post, however I thought I'd share the method I use to remove new line characters.

    s.Replace(Environment.NewLine, "");
    

    References:

    MSDN String.Replace Method and MSDN Environment.NewLine Property

    0 讨论(0)
提交回复
热议问题