設置 | 登錄 | 註冊

作者共發了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許可協議進行許可。