【问题描述】定义一个字符串类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;
}