You can return a pointer to a place in the original string after the previous replacement, and then call your function the next time using that pointer instead of the original pointer.
Note that you should generally use strncpy
instead of strcpy
everywhere in the code below, but I am trying to preserve as much of your original code as possible, so I have made simplifying assumptions.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_L 4096
char *searchAndReplace(char *text, char *search, char *replace){
char buffer[MAX_L];
char *ptr;
if(!(ptr = strstr(text, search))){
return NULL;
}
strncpy(buffer, text, ptr-text);
sprintf(buffer+(ptr-text), "%s%s", replace, ptr + strlen(search));
strcpy(text, buffer);
return ptr + strlen(search);
}
int main(){
char* original = malloc(MAX_L);
memset(original, 0, MAX_L);
strcpy(original, "The The End Is Nigh");
char* current = original;
do {
current = searchAndReplace(current, "The", "There");
} while (current);
printf("%s\n", original);
}
Output:
There There End Is Nigh