123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- #include <iostream>
- //编译预处理命令
- #include <iostream>
- #include <cstring>
- class STR{ //字符串类的定义
- private:
- char *s1, *s2; //私有成员数据,s1为原串,s2为删除重复字符的新串
- public:
- 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动态开辟的空间
- };
- //字符串类的实现
- STR::STR() {
- s1 = new char[1];
- s1[0] = '\0';
- s2 = new char[1];
- s2[0] = '\0';
- }
- STR::STR(char *str) {
- s1 = new char[strlen(str) + 1];
- strcpy(s1, str);
- s2 = new char[strlen(str) + 1];
- strcpy(s2, str);
- }
- void STR:: set(char *str) {
- delete[] s1;
- s1 = new char[strlen(str) + 1];
- strcpy(s1, str);
- }
- void STR::delsame() {
- int len = strlen(s1);
- if (len == 0) return;
- int k = 0;
- s2[k++] = s1[0];
- for (int i = 1; i < len; ++i) {
- bool isDuplicate = false;
- for (int j = 0; j < k; ++j) {
- if (s1[i] == s2[j]) {
- isDuplicate = true;
- break;
- }
- }
- if (!isDuplicate) {
- s2[k++] = s1[i];
- }
- }
- s2[k] = '\0';
- }
- void STR:: show() {
- std::cout << "原串:s1=" << s1 << std::endl;
- std::cout << "新串:s2=" << s2 << std::endl;
- }
- STR:: ~STR() {
- delete[] s1;
- delete[] s2;
- }
- //主函数测试
- int main() {
- STR test;
- char str[100];
- std::cout << "输入字符串:";
- std::cout << "\n";
- std::cin.getline(str, 100);
- test.set(str);
- test.delsame();
- test.show();
- return 0;}
|