title: Most efficient way to escape XML/HTML in C++ string?
body: <p>I can't believe this question hasn't been asked before.  I have a string that needs to be inserted into an HTML file but it may contain special HTML characters.  I want to replace these with the appropriate HTML representation.</p>
  
  <p>The code below works but is pretty verbose and ugly.  Performance is not critical for my application but I guess there are scalability problems here also.  How can I improve this?  I guess this is a job for STL algorithms or some esoteric Boost function, but the code below is the best I can come up with myself.  </p>
  
  <pre><code>void escape(std::string *data)
  {
      std::string::size_type pos = 0;
      for (;;)
      {
          pos = data-&gt;find_first_of("\"&amp;&lt;&gt;", pos);
          if (pos == std::string::npos) break;
          std::string replacement;
          switch ((*data)[pos])
          {
          case '\"': replacement = "&amp;quot;"; break;   
          case '&amp;':  replacement = "&amp;amp;";  break;   
          case '&lt;':  replacement = "&amp;lt;";   break;   
          case '&gt;':  replacement = "&amp;gt;";   break;   
          default: ;
          }
          data-&gt;replace(pos, 1, replacement);
          pos += replacement.size();
      };
  }
  </code></pre>