#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *replace(char *s, char *old, char *new)
{
  int slen = strlen(s);
  int olen = strlen(old);
  int nlen = strlen(new);
  int n;
  char *r, *p, *q, *t, *u;

  r = (char *) malloc (slen + nlen + 1);
  t = strstr(s, old);

  if (t == NULL) return strcpy(r, s);

  n = t-s;
  p = r+n;
  q = p+nlen;
  u = t+olen;
  strncpy(r, s, n);
  strcpy(p, new);
  strcpy(q, u);
  return r;
}

int main()
{
  char *s = "replace the substring";
  char *old = "the";
  char *new = "another";
  char *res;

  res = replace(s, old, new);
  printf("%s\n", res);

  return 0;
}

