Fastest way to remove chars from string

前端 未结 7 1665
生来不讨喜
生来不讨喜 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:31

    Even faster:

    public static string RemoveMultipleWhiteSpaces(string s)
        {
            char[] sResultChars = new char[s.Length];
    
            bool isWhiteSpace = false;
            int sResultCharsIndex = 0;
    
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] == ' ')
                {
                    if (!isWhiteSpace)
                    {
                        sResultChars[sResultCharsIndex] = s[i];
                        sResultCharsIndex++;
                        isWhiteSpace = true;
                    }
                }
                else
                {
                    sResultChars[sResultCharsIndex] = s[i];
                    sResultCharsIndex++;
                    isWhiteSpace = false;
                }
            }
    
            return new string(sResultChars, 0, sResultCharsIndex);
        }
    

提交回复
热议问题