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
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';
}