Strip whitespace from a string in-place?

后端 未结 3 2068
日久生厌
日久生厌 2021-02-06 04:28

I saw this in a \"list of interview questions\". Got me wondering.

Not limited to whitespace necessarily, of course, easily generalized to \"removing some specific char

3条回答
  •  我在风中等你
    2021-02-06 05:12

    C doesn't have default arguments, and if you're programming in C++ you should use std::string and remove_if from .

    You definitely can make this more efficient, by eliminating the calls to strlen, which are turning an O(N) algorithm into an O(N2) algorithm, and are totally unnecessary -- you're scanning the string anyway, so just look for the NUL yourself.

    You can also make this more C-idiomatic, by using two pointers instead of array indexing. I'd do it like this:

    void strip_char(char *str, char strip)
    {
        char *p, *q;
        for (q = p = str; *p; p++)
            if (*p != strip)
                *q++ = *p;
        *q = '\0';
    }
    

提交回复
热议问题