I'm solving some problems from a C programming book to brush up on Strings. I can't figure out why my solution is not working.
Question asks to write a function named censor that modifies a string by replacing every occurrence of foo by xxx.
My code:
int main()
{
char msg[] = "I love food, you fool.";
censor(msg);
puts(msg);
return 0;
}
void censor(char *str) {
char *c = str;
while (c+2 != '\0') {
if (*c == 'f' && *(c+1) == 'o' && *(c+2) == 'o')
*c = *(c+1) = *(c+2) = 'x';
c++;
}
}
I found that the while loop runs for like 1700 times. I'm pretty sure msg[] will include a null character automatically end of string.
You're checking the value of the pointer, not what it points to. So instead of this:
while (c+2 != '\0') {
You want this:
while (*(c+2) != '\0') {