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 character from a string, in-place".
My solution is:
void stripChar(char *str, char c = ' ') {
int x = 0;
for (int i=0;i<strlen(str);i++) {
str[i-x]=str[i];
if (str[i]==c) x++;
}
str[strlen(str)-x] = '\0';
}
I doubt there is one more efficient, but is there a solution that is more elegant?
edit: totally forgot I left strlen
in there, it is most definitely not efficient
C doesn't have default arguments, and if you're programming in C++ you should use std::string
and remove_if
from <algorithm>
.
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';
}
First of all, i<strlen(str)
is always an inefficient idiom for looping over a string. The correct loop condition is simply str[i]
, i.e. loop until str[i]
is the null terminator.
With that said, here's the simplest/most concise algorithm I know:
for (size_t i=0, j=0; s[j]=s[i]; j+=!isspace(s[i++]));
Note: My solution is for the question as written in the subject (whitespace) as opposed to the body (particular character). You can easily adapt it if needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With