【字符串类STR】

【问题描述】定义一个字符串类STR,从左到右对字符串中每个字符删除其后所有相同的字符,只留下第一次出现的那一个。例如,若字符串为"cocoon",删除重复出现的字符后,其结果是字符串"con"。

    具体要求如下:

    (1) 私有数据成员:

char *s1: 指向原字符串,存放字符串的空间需动态分配。

char *s2: 指向结果字符串,存放字符串的空间需动态分配。

    (2) 公有成员函数

STR(); //构造函数 , 用形参str所指向的字符串初始化s1

STR(char *str); //构造函数 , 用形参str所指向的字符串初始化s1

void set(char *str); //用形参str所指向的字符串设置原串s1

void delsame(); //从s1中复制没有重复的字符到s2所指向的空间

void show(); //输出s1, s2所指向的字符数组空间的字符串的内容

~STR(); //析构函数, 释放s1, s2动态开辟的空间

(3) 在主函数中定义一个STR类的对象test, 键盘输入的字符串进行测试, 通过调用成员函数完成删除工作,输出删除前后的两个字符串。

【输入形式】键盘任意输入一字符串
【输出形式】输出删除前后的两个字符串。

【样例输入】

    输入字符串:concoon

【样例输出】

    原串:s1=concoon

    新串:s2=con

【样例说明】
【评分标准】

代码如下:

#include <iostream>
#include <cstring>
using namespace std;

class STR {
private:
    char *s1, *s2;

public:
    STR() : s1(nullptr), s2(nullptr) {}
    STR(char *str);
    void set(char *str);
    void delsame();
    void show();
    ~STR();
};

STR::STR(char *str) {
    s1 = new char[strlen(str) + 1];
    strcpy(s1, str);
    s2 = nullptr;
}

void STR::set(char *str) {
    if (s1) delete[] s1;
    s1 = new char[strlen(str) + 1];
    strcpy(s1, str);
    if (s2) delete[] s2;
    s2 = nullptr;
}

void STR::delsame() {
    if (!s1) return;
    if (s2) delete[] s2;
    s2 = new char[strlen(s1) + 1];
    int len = 0;
    for (int i = 0; s1[i] != '\0'; i++) {
        bool is_duplicate = false;
        for (int j = 0; j < len; j++) {
            if (s1[i] == s2[j]) {
                is_duplicate = true;
                break;
            }
        }
        if (!is_duplicate) {
            s2[len++] = s1[i];
        }
    }
    s2[len] = '\0';
}

void STR::show() {
    cout << "原串:s1=" << (s1 ? s1 : "") << endl;
    cout << "新串:s2=" << (s2 ? s2 : "") << endl;
}

STR::~STR() {
    if (s1) delete[] s1;
    if (s2) delete[] s2;
}

int main() {
    char input[256];
    cout << "输入字符串:" << endl;
    cin >> input;
    STR test(input);
    test.delsame();
    test.show();

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

武帝为此

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值