Is there a nice and elegant way (using boost::algorithm::replace maybe?) to replace all occurrences of a character in a string – unless preceded by a backslash?
so that
std::string s1("hello 'world'");
my_replace(s1, "'", "''"); // s1 becomes "hello ''world''"
std::string s2("hello \\'world'"); // note: only a single backslash in the string
my_replace(s2, "'", "''"); // s2 becomes "hello \\'world''"
Using boost::regex, this can be done using:
std::string my_replace (std::string s, std::string search, std::string format) {
boost::regex e("([^\\\\])" + search);
return boost::regex_replace(s, e, "\\1" + format);
}
But I prefer not to use boost::regex due to performance reasons. boost::algorithm::replace looks like a good fit, but I can’t figure out exactly how.
Here is a simple algorithm that does the job:
UPDATE:
Following @BenVoigt’s suggestion, I reformulated the algorithm to avoid in-place operations. That should bring further performance improvement: