用過python的朋友應該知道,python的string中有個replace函數,其功能是實現字串的替換,預設情況下是替換所有,如果加入參數的話會根據設定的個數進行替換,比如下面的例子:
>>> import string
>>> str1 = "ab1ab2ab3ab4"
>>> print string.replace(str1,"ab","cd")
cd1cd2cd3cd4
>>> print string.replace(str1,"ab","cd",1)
cd1ab2ab3ab4
>>> print string.replace(str1,"ab","cd",2)
cd1cd2ab3ab4
>>>
在c++中,我也想這麼用……暫時還沒找到現成的,就自己寫了個。
這裡貼出來函數的代碼,也方便我以後使用:
string m_replace(string str,string pattern,string dstPattern,int count=-1){ string retStr=""; string::size_type pos; int i=0,l_count=0,szStr=str.length(); if(-1 == count) // replace all count = szStr; for(i=0; i<szStr; i++) { if(string::npos == (pos=str.find(pattern,i))) break; if(pos < szStr) { retStr += str.substr(i,pos-i) + dstPattern; i=pos+pattern.length()-1; if(++l_count >= count) { i++; break; } } } retStr += str.substr(i); return retStr;}
補充:
當時我認為STL的replace函數不能進行不同長度的替換(現在證明是錯的),所以就沒用……
這裡有用STL的replace函數的實現:
View Code
#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;}