Header

Wednesday 14 August 2013

Write the function strreplace(s, chr, repl_chr) which will replace each occurrences of character chr with the character repl_chr in the string s. The function returns the number of replacements. Place the source code of this function in a file named strreplace.c

Write the function strreplace(s, chr, repl_chr) which will replace each occurrences of character chr with the character repl_chr in the string s. The function returns the number of replacements. Place the source code of this function in a file named strreplace.c

char *replace_str(const char *str, const char *old, const char *new)
{
 char *ret, *r;
 const char *p, *q;
 size_t oldlen = strlen(old);
 size_t count, retlen, newlen = strlen(new);

 if (oldlen != newlen) {
  for (count = 0, p = str; (q = strstr(p, old)) != NULL; p = q + oldlen)
   count++;
  /* this is undefined if p - str > PTRDIFF_MAX */
  retlen = p - str + strlen(p) + count * (newlen - oldlen);
 } else
  retlen = strlen(str);

 if ((ret = malloc(retlen + 1)) == NULL)
  return NULL;

 for (r = ret, p = str; (q = strstr(p, old)) != NULL; p = q + oldlen) {
  /* this is undefined if q - p > PTRDIFF_MAX */
  ptrdiff_t l = q - p;
  memcpy(r, p, l);
  r += l;
  memcpy(r, new, newlen);
  r += newlen;
 }
 strcpy(r, p);

 return ret;
}

No comments:

Post a Comment