字符串替换(C++)

 2023-09-10 阅读 14 评论 0

摘要:用过python的朋友应该知道,python的string中有个replace函数,其功能是实现字符串的替换,默认情况下是替换所有,如果加入参数的话会根据设定的个数进行替换,比如下面的例子: >>> import string >>> str1 = &#

用过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函数的实现:

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

转载于:https://www.cnblogs.com/MikeZhang/archive/2012/09/22/cppReplaceFunction20120922.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/34433.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息