title: Replacing all occurrences of a substring with another substring in a long string
body: <p>I'm writing a function, which takes three parameters:</p>
  
  <ul>
  <li><code>target</code> : Target String</li>
  <li><code>oldVal</code> : Old substring</li>
  <li><code>newVal</code> : New Substring (To replace the oldVal)</li>
  </ul>
  
  <p>The task of this function is to find all the occurrence of <code>oldVal</code> in <code>target</code> string, and replace them with <code>newVal</code>.</p>
  
  <p>This is the function I've got at the moment:</p>
  
  <pre><code>std::string replace_old_with_new(std::string target, std::string oldVal, std::string newVal) {
  
      std::cout &lt;&lt; "target : " &lt;&lt; target &lt;&lt; ", oldVal: " &lt;&lt; oldVal &lt;&lt; ", newVal: " &lt;&lt; newVal &lt;&lt; "\n";
      std::string::iterator begin = target.begin();
      std::string::iterator oldValBegin = oldVal.begin();
  
      while (begin != target.end()) {
          if (*begin == *oldValBegin) {
              target = target.replace(begin, begin + oldVal.size(), oldVal);
              begin = target.begin();
          } else {
              ++begin;
          }
      }
  
      return target;
  }
  </code></pre>
  
  <p>The following call to the above function:</p>
  
  <pre><code>replace_old_with_new("Hello! hi hi!", "hi", "bye");
  </code></pre>
  
  <p>should return the string - </p>
  
  <pre><code>"Hello! bye bye!"
  </code></pre>
  
  <p>But, when I run the code, nothing happens. It seems like I'm stuck in an infinite loop. The cursor keeps blinking on terminal. Is something wrong with my function. I think what might be troubling is the <code>replace</code> call in the <code>if</code> block. Is that the correct way to use iterator range in the <code>replace</code> function call? I can do this with <code>erase</code> and <code>insert</code>. But I want to use <code>replace</code> here.</p>