您的位置:首页 > 其它

string类自定义字符串替换函数replace

2013-11-20 22:21 507 查看
#include <iostream>

#include <string>

using namespace std;

/*

* 函数功能:将string字符串中的某些字符替换成其他字符

* 参数说明: str 原字符串 strFind 需要替换字符串 strReplace 替换字符串

*/

string replace(string &str,const string &strFind,const string &strReplace)

{

int fsize = strFind.size();

int rsize = strReplace.size();

int pos = str.find(strFind,0);//从开始位置查找第一个符合的字符串,未找到返回str.npos

while (pos!=str.npos)

{

str.replace(pos,rsize,strReplace); //替换查找到的字符串

pos = str.find(strFind,pos+fsize); //继续查找

}

return str;

}

int main(int argc, char* argv[])

{

string str="abc[def[gef[ee[";

string strFind ="[";

string strReplace="(";

replace(str,strFind,strReplace); //将字符串str中的“[”替换为“(”

cout<<str<<endl;

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: