title: Recursive C String replace
body: <p>I'm quite new to C programming, used to only use C++ with the String class, but I'm wondering how I would go about doing a recursive replacement of a string with another string.</p>
  
  <p>My code is like this, but it doesn't seem to work correctly and I cannot quite pin down where it fails. It works fine on one replacement, but more than one and it fails.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  
  char *replace_str(char *str, char *orig, char *rep)
  {
      int current_index = 0;
      static char buffer[10000];
  
      if (!strstr(str, orig))  // Is 'orig' even in 'str'?
      {
          return str;
      }
  
      while (1)
      {        
          char *p;
  
          if (!(p = strstr(str + current_index, orig)))  // Is 'orig' even in 'str'?
          {
              return buffer;
          }
  
          strncpy(buffer, str, p-str); // Copy characters from 'str' start to 'orig' st$
          buffer[p-str] = '\0';
  
          sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig));
  
  
          printf("%d -&gt; %s\n", current_index, buffer);
  
          current_index = (p - str) + strlen(rep);
  
          str = buffer;
      }
  
      return buffer;
  }
  
  int main(void)
  {
      puts(replace_str("hello world world", "world", "world2"));
  
      return 0;
  }
  </code></pre>
  
  <p>With this example, it prints this:</p>
  
  <pre><code> 0 -&gt; hello world2 world
  12 -&gt; hello world2 world22
  hello world2 world22
  </code></pre>