随笔 - 272  文章 - 0  评论 - 283  阅读 - 142万

字符串替换(C++)

用过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;

}
复制代码
posted on   Mike_Zhang  阅读(7777)  评论(9编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2012年9月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 1 2 3 4 5 6

点击右上角即可分享
微信分享提示