If you want to do this in general, without worrying about trying to determine the size of your buffers, you must malloc create a new line large enough to hold the result:
char *replace(const char *s, char ch, const char *repl) { int count = 0; const char *t; for(t=s; *t; t++) count += (*t == ch); size_t rlen = strlen(repl); char *res = malloc(strlen(s) + (rlen-1)*count + 1); char *ptr = res; for(t=s; *t; t++) { if(*t == ch) { memcpy(ptr, repl, rlen); ptr += rlen; } else { *ptr++ = *t; } } *ptr = 0; return res; }
Using:
int main() { char *s = replace("aaabaa", 'b', "ccccc"); printf("%s\n", s); free(s); return 0; }
source share