// 替换字符串中的所有指定字符串
string& replace_all(string& str, const string& old_value, const string& new_value)
{
while (true)
{
string::size_type pos(0);
if ((pos = str.find(old_value)) != string::npos)
str.replace(pos, old_value.length(), new_value);
else
break;
}
return str;
}
https://www.cnblogs.com/lpxblog/p/9855791.html
注意:如果 目标字符串(new_value) 中含有 查询字符串(old_value),则函数将陷入死循环。因为函数的原理是替换了一次字符串之后在新的字符串中从头查询,遇到目标字符串后,由于目标字符串中含有查询字符串,会导致再次替换,如此往复。
增强版(不会出现上述问题,自己写的):
// 替换字符串中的所有指定子串
std::wstring& replace_all(std::wstring& str, const std::wstring& old_value, const std::wstring& new_value)
{
size_t sizeOld = old_value.length(), sizeNew = new_value.length(), pos = 0;
while ((pos = str.find(old_value, pos + sizeNew)) != std::wstring::npos)
str.replace(pos, sizeOld, new_value);
return str;
}