Fastest way to remove white spaces in string

后端 未结 13 1210
粉色の甜心
粉色の甜心 2020-11-27 18:39

I\'m trying to fetch multiple email addresses seperated by \",\" within string from database table, but it\'s also returning me whitespaces, and I want to remove the whitesp

13条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 19:00

    I would build a custom extension method using StringBuilder, like:

    public static string ExceptChars(this string str, IEnumerable toExclude)
    {
        StringBuilder sb = new StringBuilder(str.Length);
        for (int i = 0; i < str.Length; i++)
        {
            char c = str[i];
            if (!toExclude.Contains(c))
                sb.Append(c);
        }
        return sb.ToString();
    }
    

    Usage:

    var str = s.ExceptChars(new[] { ' ', '\t', '\n', '\r' });
    

    or to be even faster:

    var str = s.ExceptChars(new HashSet(new[] { ' ', '\t', '\n', '\r' }));
    

    With the hashset version, a string of 11 millions of chars takes less than 700 ms (and I'm in debug mode)

    EDIT :

    Previous code is generic and allows to exclude any char, but if you want to remove just blanks in the fastest possible way you can use:

    public static string ExceptBlanks(this string str)
    {
        StringBuilder sb = new StringBuilder(str.Length);
        for (int i = 0; i < str.Length; i++)
        {
            char c = str[i];
            switch (c)
            {
                case '\r':
                case '\n':
                case '\t':
                case ' ':
                    continue;
                default:
                    sb.Append(c);
                    break;
            }
        }
        return sb.ToString();
    }
    

    EDIT 2 :

    as correctly pointed out in the comments, the correct way to remove all the blanks is using char.IsWhiteSpace method :

    public static string ExceptBlanks(this string str)
    {
        StringBuilder sb = new StringBuilder(str.Length);
        for (int i = 0; i < str.Length; i++)
        {
            char c = str[i];
            if(!char.IsWhiteSpace(c))
                sb.Append(c);
        }
        return sb.ToString();
    }
    

提交回复
热议问题