字符串替換(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;

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM