Fastest way to remove chars from string

前端 未结 7 1697
生来不讨喜
生来不讨喜 2020-12-05 13:52

I have a string from which I have to remove following char: \'\\r\', \'\\n\', and \'\\t\'. I have tried three different ways of removing these char and benchmarked them so I

7条回答
  •  甜味超标
    2020-12-05 14:46

    I believe you'll get the best possible performance by composing the new string as a char array and only convert it to a string when you're done, like so:

    string s = "abc";
    int len = s.Length;
    char[] s2 = new char[len];
    int i2 = 0;
    for (int i = 0; i < len; i++)
    {
        char c = s[i];
        if (c != '\r' && c != '\n' && c != '\t')
            s2[i2++] = c;
    }
    return new String(s2, 0, i2);
    

    EDIT: using String(s2, 0, i2) instead of Trim(), per suggestion

提交回复
热议问题