目前共有4篇帖子。 內容轉換:不轉換▼
 
點擊 回復
241 3
【方法】通过派生std::string类的方法给string类添加替换全部字符串的replace重载函数
一派護法 十九級
1樓 發表于:2016-6-20 21:39

#include <iostream>
#include <string>

using namespace std;

class string_ex : public string
{
public:
    using string::replace; // 继承父类的全部replace重载函数

    string_ex(const char *s);
    void replace(const char *s1, const char *s2);
};

string_ex::string_ex(const char *s) : string(s)
{
}

void string_ex::replace(const char *s1, const char *s2)
{
    int len1 = strlen(s1);
    int len2 = strlen(s2);
    int pos = 0;
    while ((pos = find(s1, pos)) != -1)
    {
        replace(pos, len1, s2);
        pos += len2;
    }
}

int main(void)
{
    string_ex str = "this is a string.";
    str.replace("is", "IS");
    cout << str << endl;

    str.replace("t", "M");
    cout << str << endl;

    str = "12212";
    str.replace("12", "21");
    cout << str << endl;

    str = "mmmmmm";
    str.replace("m", "n");
    cout << str << endl;
}


一派護法 十九級
2樓 發表于:2016-6-20 21:40


父类string的replace重载函数都被继承了。
一派護法 十九級
3樓 發表于:2016-6-20 21:44

C++规定:禁止用户修改库中的类,即便是添加函数也不行。
所以创建这些类的派生类是一个不错的选择。
一派護法 十九級
4樓 發表于:2016-6-20 21:58

【添加 -= 运算符重载】
#include <iostream>
#include <string>

using namespace std;

class string_ex : public string
{
public:
    using string::replace; // 继承父类的全部replace重载函数

    string_ex(const char *s);
    void replace(const char *s1, const char *s2);

    bool operator -= (const char *s);
};

string_ex::string_ex(const char *s) : string(s)
{
}

void string_ex::replace(const char *s1, const char *s2)
{
    size_t len1 = strlen(s1);
    size_t len2 = strlen(s2);
    size_type pos = 0;
    while ((pos = find(s1, pos)) != -1)
    {
        replace(pos, len1, s2);
        pos += len2;
    }
}

bool string_ex::operator -= (const char *s)
{
    size_type len = length();
    size_t slen = strlen(s);
    if (len > slen)
    {
        size_t n = len - slen;
        const char *p = data();
        if (strcmp(p + n, s) == 0)
        {
            char *mem = new char[n];
            memcpy(mem, p, n);
            assign(mem, n);
            delete[] mem;
            return true;
        }
    }
    return false;
}

int main(void)
{
    string_ex str = "this is a string.";
    if (str -= "string.")
        cout << str << endl;
   
    if (str -= "a")
        cout << str << endl;
}


回復帖子

內容:
用戶名: 您目前是匿名發表
驗證碼:
(快捷鍵:Ctrl+Enter)
 

本帖信息

點擊數:241 回複數:3
評論數: ?
作者: 巨大八爪鱼
最後回復:巨大八爪鱼
最後回復時間:2016-6-20 21:58
 
©2010-2024 Arslanbar Ver2.0
除非另有聲明,本站採用創用CC姓名標示-相同方式分享 3.0 Unported許可協議進行許可。