I'm trying to make a function in C to replace all occurrences of a substring in a string. I made my function, but it only works on the first occurrence of the substring in the bigger string.
Here is the code so far:
void strreplace(char string*, char search*, char replace*) {
char buffer[100];
char *p = string;
while ((p = strstr(p, search))) {
strncpy(buffer, string, p-string);
buffer[p-string] = '\0'; //EDIT: THIS WAS MISSING
strcat(buffer, replace);
strcat(buffer, p+strlen(search));
strcpy(string, buffer);
p++;
}
}
I'm not new to C programming, but I'm missing something here.
Example: for input string "marie has apples has", searching for "has" and replace with "blabla"
In the first "has" is replaced correctly, but the second one is not. The final output is "marie blabla apples hasblabla". Notice the second "has" is still there.
What am I doing wrong? :)
EDIT Is is working now. Adding the null terminating character fixed the problem. I know the resulting string can be bigger than 100. It's a school homework so I won't have strings longer than 20 or so.
while
loop only incrementsp
by 1 each time through the loop. I would assume it needs to bump by the length of the replacement string.strcat(buffer, p+strlen(search));
andstrcpy(string, buffer);
are for? You don't really need the first line, and you can move the second one out of the loop…