title: Locating and replacing a substring (C language)
body: <p>I wrote the following code with the intention of using pointer arithmetic on strings to find, and replace, a targeted substring. Obviously, it's not elegant, but unfortunately it's also incorrect - it adds extraneous characters to the string.  </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  
  int main() {
      char string[] = "The quick brown fox jumped over the lazy dog.";
      char target[] = "brown"
      char replacement[] = "ochre";
      char segment[80+1];
      char pre_segment[80+1];
      char post_segment[80+1];
      int S = strlen(string), T = strlen(target);
      for (int i = 0; i &lt; S; i++) {
          strncpy(segment, string + i, T);
          if (strcmp(segment, target) == 0) {
          &gt;&gt;&gt; strncpy(pre_segment, string, i); &lt;&lt;&lt;
              strncpy(post_segment, string + i + T,
                  S - (i + T));
              strcat(pre_segment, replacement);
              strcat(pre_segment, post_segment);
              printf("%s\n", pre_segment);
          }
      }
      return 0; 
  }
  </code></pre>
  
  <p>After the line marked like >>>this&lt;&lt;&lt;, extraneous characters have been prepended to replacement before replacement is concatenated with pre_segment.</p>
  
  <p>Can someone give me suggestions on how to debug this? (Suggestions for a nicer solution are also welcome, but please try to be explicit. Also, I'm not supposed to be using dynamic memory allocation for this.)</p>