Erik Blenert Erik Blenert - 4 years ago 141
C Question

Replace all occurrences of a substring in a string in C

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);

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? :)

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.

alk alk
Answer Source

For starters:

This line

strncpy(buffer, string, p-string);

not necessarily appends a 0-terminator to what had been copied to buffer.

The following line

strcat(buffer, replace);

however relies on buffer being 0-terminated.

As buffer had not been initialised and though the 0-terminator most likely misses the latter line may very well read beyond buffer's memory and with this invoke the infamous Undefined Behaviour.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download