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

#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;
    }
} 

运行结果:
这里写图片描述

展开阅读全文

没有更多推荐了,返回首页