設置 | 登錄 | 註冊

作者共發了4篇帖子。

【方法】通过派生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;
}


內容轉換:

回覆帖子
內容:
用戶名: 您目前是匿名發表。
驗證碼:
看不清?換一張
©2010-2025 Purasbar Ver3.0 [手機版] [桌面版]
除非另有聲明,本站採用知識共享署名-相同方式共享 3.0 Unported許可協議進行許可。