直接上代码了!
// 字符串替换函数
#include <string>
/**
* 字符串替换函数
* #function name : replace_str()
* #param str : 操作之前的字符串
* #param before : 将要被替换的字符串
* #param after : 替换目标字符串
* #return : void
*/
void replace_str(std::string& str, const std::string& before, const std::string& after)
{
for (std::string::size_type pos(0); pos != std::string::npos; pos += after.length())
{
pos = str.find(before, pos);
if (pos != std::string::npos)
str.replace(pos, before.length(), after);
else
break;
}
}
测试程序如下:
int main()
{
string str = "String replace test. before = author.";
string before = "before";
string after = "after";
replace_str(str, before, after);
before = "author";
after = "Shaoguang";
replace_str(str, before, after);
// result is "String replace test. after = Shaoguang."
cout << str << endl;
return 0;
}