#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++)