用过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 allcount = 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; }
补充:
vim替换字符串?当时我认为STL的replace函数不能进行不同长度的替换(现在证明是错的),所以就没用……
这里有用STL的replace函数的实现:
#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 allcount = 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;}