title: std::string replace "&" with "&amp;"
body: <p>I have to replace all occurrences of only <code>&amp;</code> with <code>&amp;amp;</code> in a string.
  But I have to skip it if <code>&amp;</code> is followed by a <code>;</code>, i.e. if <code>&amp;amp;</code> or <code>&amp;engrave;</code> etc. is there it is not to be modified.</p>
  
  <p>I have written the <a href="http://cpp.sh/6o5mq" rel="nofollow">following code</a> and it seems to be working well, but I'm doing too many comparisons I think - is there a better way do it? I can use boost or c++11.</p>
  
  <pre><code>#include &lt;string&gt;
  #include &lt;iostream&gt;
  
  int main()
  {
      std::string str = "An R&amp;D string with one more R&amp;amp;D here and S&amp;D or T&amp;engrave; Some More T&amp;D and &amp;amp;&amp;engrave; and R&amp;&amp;D";
      std::cout&lt;&lt;"original string is : "&lt;&lt;str&lt;&lt;std::endl;
      int index = 0;
      while(1)
      {
          std::string::size_type n = str.find("&amp;",index);
          if(n == std::string::npos)
              break;
          std::string sub = str.substr(n+1, 10);
          std::string::size_type m = sub.find("&amp;");
          std::string::size_type b = sub.find(";");
          if(m != std::string::npos &amp;&amp; m&lt;b)
          {
              auto temp = sub.substr(0,m-1);
              sub = temp;
          }
          if(sub.find(";") == std::string::npos)
          {
              str.replace(n, 1, "&amp;amp;");
          }
           index = n+1;
      }
      std::cout&lt;&lt;"changed string is : "&lt;&lt;str&lt;&lt;std::endl;
  }
  </code></pre>