您的位置:首页 > 编程语言 > C语言/C++

C++实现string.replace(字符串替换)

2017-10-28 16:40 1011 查看
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

void string_replace( std::string &strBig, const std::string &strsrc, const std::string &strdst);

int _tmain(int argc, _TCHAR* argv[])
{
std::string strContent = "This is a Test";

string_replace(strContent, "Test", "demo");

cout << strContent << endl;

system("pause");

return 0;
}

//************************************
// Method:    string_replace
// FullName:  string_replace
// Access:    public
// Returns:   void
// Qualifier: 把字符串的strsrc替换成strdst
// Parameter: std::string & strBig
// Parameter: const std::string & strsrc
// Parameter: const std::string & strdst
//************************************
void string_replace( std::string &strBig, const std::string &strsrc, const std::string &strdst)
{
std::string::size_type pos = 0;
std::string::size_type srclen = strsrc.size();
std::string::size_type dstlen = strdst.size();

while( (pos=strBig.find(strsrc, pos)) != std::string::npos )
{
strBig.replace( pos, srclen, strdst );
pos += dstlen;
}
}


运行结果:

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