功能:将一段字符串中特定的子字符串替换成指定字符串数组中的的字符串
详情请见程序中的注释。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/*
功能:将一段字符串中特定的子字符串替换成指定字符串数组中的的字符串
content:原来的字符串(原文)
repStr:原文中要被替换成新字符串的旧字符串(关键字)
vec:替换旧字符串的新字符串数组
返回值:完成替换后的新字符串
*/
string ReplaceString(const string &content, const string &repStr,
const vector<string> &vec)
{
string res = content;
int len, pos;
pos = 0;
len = repStr.length();
for(size_t i=0; i<vec.size(); i++)
{
pos = res.find(repStr, pos);
if( string::npos == pos )
break;
res.replace(pos, len, vec[i]);
}
return res;
}
//测试程序
int main()
{
string str = "sadf,,regterl..r,,dslf,,dfadfa.,,..";
vector<string> vec;
vec.push_back("AAA");
vec.push_back("BBB");
vec.push_back("CCC");
vec.push_back("DDD");
cout << ReplaceString(str, ",,", vec) << endl;
return 0;
}