How to replace all occurrences of one character with two characters using std::string?

WilliamKF picture WilliamKF · Apr 9, 2011 · Viewed 27.6k times · Source

Is there a nice simple way to replace all occurrences of "/" in a std::string with "\/" to escape all the slashes in a std::string?

Answer

UncleBens picture UncleBens · Apr 9, 2011

Probably the simplest way to get this done is with boost string algorithms library.

  boost::replace_all(myString, "/", "\\/");

  std::string result = boost::replace_all_copy(myString, "/", "\\/");