title: C: Replacing a substring within a string using loops
body: <p>I am struggling with the concept of replacing substrings within strings. This particular exercise does not want you to use built in functions from <code>&lt;string.h&gt;</code> or <code>&lt;strings.h&gt;</code>.</p>
  
  <p>Given the string made up of two lines below:</p>
  
  <pre><code>"Mr. Fay, is this going to be a battle of wits?" 
  "If it is," was the indifferent retort, "you have come unarmed!"
  </code></pre>
  
  <p>I have to replace a substring with another string.</p>
  
  <p>This is what I have so far, and I'm having trouble copying the substring to a new array, and replacing the substring with the new string:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  
  int dynamic();
  
  int main()
  {
      char str[]="\n\"Mr. Fay, is this going to be a battle of wits?\" \n\"If it is,\" was the indifferent retort, \"you have come unarmed!\"";
  
      int i, j=0, k=0, l=0, n=0;
      unsigned int e = n-2;
  
      char data[150];
      char newData[150];
      char newStr[150];
  
      printf("Give me a substring from the string");
      gets(data);
  
      printf("Give me a substring to replace it with");
      gets(newData);
  
      dynamic();
  
      for (i=0; str[i] != '\0'; i++)
      {
          if (str[i] != data[j])
          {
              newStr[l] = str[i];
              l++;
          }
          else if ((str[i+e] == data[j+e]) &amp;&amp; (j&lt;n))
          {
              newStr[l] = newData[j];
              j++;
              l++;
              e--;
          }
          else if ((str[i+e] == data[j+e]) &amp;&amp; (j&gt;=n))
          {
              j++;
              e--;
          }
          else
          {
              newStr[l] = str[i];
              l++;
          }
      }
  
      printf("original string is-");
  
      for (k=0; k&lt;n; k++)
          printf("%c",str[k]);
      printf("\n");
  
      printf("modified string is-");
  
      for(k=0; k&lt;n; k++)
          printf("%c",newStr[k]);
      printf("\n");
  }
  
  int dynamic()
  {
      char str[]="\n\"Mr. Fay, is this going to be a battle of wits?\" \n\"If it is,\" was the indifferent retort, \"you have come unarmed!\"";
  
      int i, n=0;
  
      for (i=0; str[i] != '\0'; i++)
      {
          n++;
      }
      printf("the number of characters is %d\n",n);
  
      return (n);
  }
  </code></pre>