Skip to main content

There are countless ways to trim all whitespace from a string in C#, but these are the fastest.

//
// Fastest (unsafe/unmanaged), Method: "TrimAllWithStringInplace", Benchmark: "STRING INPLACE"
// see: https://www.codeproject.com/Articles/1014073/Fastest-method-to-remove-all-whitespace-from-Strin
public static unsafe string StripWhiteSpace(string str)
{
    fixed (char* pfixed = str)
    {
        char* dst = pfixed;
        for (char* p = pfixed; *p != 0; p++)
            switch (*p)
            {
                case '\u0020': case '\u00A0': case '\u1680': case '\u2000': case '\u2001':
                case '\u2002': case '\u2003': case '\u2004': case '\u2005': case '\u2006':
                case '\u2007': case '\u2008': case '\u2009': case '\u200A': case '\u202F':
                case '\u205F': case '\u3000': case '\u2028': case '\u2029': case '\u0009':
                case '\u000A': case '\u000B': case '\u000C': case '\u000D': case '\u0085':
                    continue;
                default:
                    *dst++ = *p;
                    break;
            }

        return new string(pfixed, 0, (int)(dst - pfixed));
    }
}

//
// Fastest (safe/managed), Method: "TrimAllWithCharArrayCopy", Benchmark: "ARRAY COPY"
// see: https://www.codeproject.com/Articles/1014073/Fastest-method-to-remove-all-whitespace-from-Strin
public static string StripWhiteSpace(string str)
{
    var len = str.Length;
    var src = str.ToCharArray();
    int srcIdx = 0, dstIdx = 0, count = 0;

    for (int i = 0; i < len; i++)
    {
        switch (src[i])
        {
            case '\u0020': case '\u00A0': case '\u1680': case '\u2000': case '\u2001':
            case '\u2002': case '\u2003': case '\u2004': case '\u2005': case '\u2006':
            case '\u2007': case '\u2008': case '\u2009': case '\u200A': case '\u202F':
            case '\u205F': case '\u3000': case '\u2028': case '\u2029': case '\u0009':
            case '\u000A': case '\u000B': case '\u000C': case '\u000D': case '\u0085':
                count = i - srcIdx;
                Array.Copy(src, srcIdx, src, dstIdx, count);
                srcIdx += count + 1;
                dstIdx += count;
                len--;
                continue;
            default:
                break;
        }

    if (dstIdx < len)
        Array.Copy(src, srcIdx, src, dstIdx, len - dstIdx);

    return new string(src, 0, len);
}