str.c (904B)
1 /* Taken from: http://creativeandcritical.net/str-replace-c/ */ 2 /* Released in the public domain */ 3 #include <stddef.h> 4 #include <stdlib.h> 5 #include <string.h> 6 7 char * 8 replace_str(const char *str, const char *old, const char *new) 9 { 10 char *ret, *r; 11 const char *p, *q; 12 size_t oldlen = strlen(old); 13 size_t count, retlen, newlen = strlen(new); 14 15 if (oldlen != newlen) { 16 for (count = 0, p = str; (q = strstr(p, old)) != NULL; p = q + oldlen) 17 count++; 18 /* this is undefined if p - str > PTRDIFF_MAX */ 19 retlen = p - str + strlen(p) + count * (newlen - oldlen); 20 } else 21 retlen = strlen(str); 22 23 if ((ret = malloc(retlen + 1)) == NULL) 24 return NULL; 25 26 for (r = ret, p = str; (q = strstr(p, old)) != NULL; p = q + oldlen) { 27 /* this is undefined if q - p > PTRDIFF_MAX */ 28 ptrdiff_t l = q - p; 29 memcpy(r, p, l); 30 r += l; 31 memcpy(r, new, newlen); 32 r += newlen; 33 } 34 strcpy(r, p); 35 36 return ret; 37 }