C/C++教程

c++字符串替换

本文主要是介绍c++字符串替换,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#include <string>
#include <iostream>

using namespace std;

string m_replace(string strSrc,
                 const string &oldStr, const string &newStr,int count=-1)
{
    string strRet=strSrc;
    size_t pos = 0;
    int l_count=0;
    if(-1 == count) // replace all
        count = strRet.size();
    while ((pos = strRet.find(oldStr, pos)) != string::npos)
    {
        strRet.replace(pos, oldStr.size(), newStr);
        if(++l_count >= count) break;
        pos += newStr.size();
    }
    return strRet;
}

int main()
{
    string str1="ab1ab2ab3";
    string str2="ab";
    string str3="cd";
    string str4="cdefgh";

    cout<<m_replace(str1,str2,str3)<<endl;
    cout<<m_replace(str1,str2,str3,1)<<endl;
    cout<<m_replace(str1,str2,str4)<<endl;
    cout<<m_replace(str1,str2,str4,2)<<endl;

}

代码来源:字符串替换(C++)

这篇关于c++字符串替换的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!