c++关于字符串的替换

来源:互联网 发布:阿里云备案拍照 编辑:程序博客网 时间:2024/05/17 23:31

在c Java语言中,有replace 这个函数,可以用于字符串替换,但是c++却没有类似的功能

str 要处理的字符串  pattern  要替换的字符串  dstPattern 替换成为的字符串 count 替换个数

#include <iostream>
#include <string>
using namespace std;


string m_replace(string str,string pattern,string dstPattern,int count=-1)
{
    string retStr="";
    int pos;


    int szStr=str.length();
    int szPattern=pattern.size();
    int i=0;
    int l_count=0;
    if(-1 == count) // replace all
        count = szStr;


    for(i=0; i<szStr; i++)
    {
        pos=str.find(pattern,i);


        if(std::string::npos == pos)
            break;
        if(pos < szStr)
        {
            std::string s=str.substr(i,pos-i);
            retStr += s;
            retStr += dstPattern;
            i=pos+pattern.length()-1;
            if(++l_count >= count)
            {
                i++;
                break;
            }
        }
    }
    retStr += str.substr(i);
    return retStr;
}

0 0
原创粉丝点击