作者共发了4篇帖子。 内容转换:不转换▼
 
点击 回复
270 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)
 

本帖信息

点击数:270 回复数:3
评论数: ?
作者:巨大八爪鱼
最后回复:巨大八爪鱼
最后回复时间:2016-6-20 21:58
 
©2010-2024 Arslanbar Ver2.0
除非另有声明,本站采用知识共享署名-相同方式共享 3.0 Unported许可协议进行许可。