Possible Duplicate:
how to replace substring in c?
I have tried looking for a better solution for this problem. There are codes available but all for C++. Not to forget this is very simple and basic in Java. I wanted a great optimal solution in C?
Any help will be greatly appreciated! Thanks!
Simple solution found on google: http://www.linuxquestions.org/questions/programming-9/replace-a-substring-with-another-string-in-c-170076/
Edit: Taking your specification into account, I've edited the code in the link to this:
char *replace_str(char *str, char *orig, char *rep, int start)
{
static char temp[4096];
static char buffer[4096];
char *p;
strcpy(temp, str + start);
if(!(p = strstr(temp, orig))) // Is 'orig' even in 'temp'?
return temp;
strncpy(buffer, temp, p-temp); // Copy characters from 'temp' start to 'orig' str
buffer[p-temp] = '\0';
sprintf(buffer + (p - temp), "%s%s", rep, p + strlen(orig));
sprintf(str + start, "%s", buffer);
return str;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With