直接上代码了,谁实话只有被坑了才想到优化,不打不动啊。
std::string StrAllreplace(std::string resource_str, std::string sub_str, std::string new_str)
{
std::string dst_str = resource_str;
std::string::size_type pos = 0;
bool bfind = false;
//判断替换的字符是否包含原字符 包含的话下方的循环替换会进入死循环
if (sub_str.find(new_str) != std::string::npos || new_str.find(sub_str) != std::string::npos)
bfind = true;
if (bfind)
{
//换成中间值,替换后在用新字符去替换中间值
std::string tempdate = "temp_sample_data";
while ((pos = dst_str.find(sub_str)) != std::string::npos)
{
dst_str.replace(pos, sub_str.length(), tempdate);
}
while ((pos = dst_str.find(tempdate)) != std::string::npos)
{
dst_str.replace(pos, tempdate.length(), new_str);
}
}
else {
while ((pos = dst_str.find(sub_str)) != std::string::npos)
{
dst_str.replace(pos, sub_str.length(), new_str);
}
}
return dst_str;
}