How to replace a substring in C when the substring is similar to the replacement string? -


i've created program in c uses strstr, strncpy, , sprintf functions replace substrings replacement string. flaw program when looking replace e.g. searching "the" , wanting replace "there", causes infinite loop, program keeps finding replaced. how fix in c, or there way implement such function in c? thanks.

replacement function: (its called multiple times until there no longer matches found).

char *searchandreplace(char *text, char *search, char *replace){   char buffer[max_l];     char *ptr;     char *modtext = malloc(4096);     if(!(ptr = strstr(text, search))){         return;     }     strncpy(buffer, text, ptr-text);     sprintf(buffer+(ptr-text), "%s%s", replace, ptr + strlen(search));     strcpy(text, buffer); 

you can return pointer place in original string after previous replacement, , call function next time using pointer instead of original pointer.

note should use strncpy instead of strcpy everywhere in code below, trying preserve of original code possible, 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 end nigh");       char* current = original;     {         current = searchandreplace(current, "the", "there");     } while (current);      printf("%s\n", original); } 

output:

there there end nigh 

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -