How do I Search/Find and Replace in a standard string?

Adam Tegen picture Adam Tegen · Sep 29, 2009 · Viewed 112.3k times · Source

Is there a way to replace all occurrences of a substring with another string in std::string?

For instance:

void SomeFunction(std::string& str)
{
   str = str.replace("hello", "world"); //< I'm looking for something nice like this
}

Answer

ilyaigpetrov picture ilyaigpetrov · Nov 27, 2010
#include <boost/algorithm/string.hpp> // include Boost, a C++ library
...
std::string target("Would you like a foo of chocolate. Two foos of chocolate?");
boost::replace_all(target, "foo", "bar");

Here is the official documentation on replace_all.