字符串类STR.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include <iostream>
  2. //编译预处理命令
  3. #include <iostream>
  4. #include <cstring>
  5. class STR{ //字符串类的定义
  6. private:
  7. char *s1, *s2; //私有成员数据,s1为原串,s2为删除重复字符的新串
  8. public:
  9. STR(); //构造函数 , 用形参str所指向的字符串初始化s1
  10. STR(char *str); //构造函数 , 用形参str所指向的字符串初始化s1
  11. void set(char *str); //用形参str所指向的字符串设置原串s1
  12. void delsame(); //从s1中复制没有重复的字符到s2所指向的空间
  13. void show(); //输出s1, s2所指向的字符数组空间的字符串的内容
  14. ~STR(); //析构函数, 释放s1, s2动态开辟的空间
  15. };
  16. //字符串类的实现
  17. STR::STR() {
  18. s1 = new char[1];
  19. s1[0] = '\0';
  20. s2 = new char[1];
  21. s2[0] = '\0';
  22. }
  23. STR::STR(char *str) {
  24. s1 = new char[strlen(str) + 1];
  25. strcpy(s1, str);
  26. s2 = new char[strlen(str) + 1];
  27. strcpy(s2, str);
  28. }
  29. void STR:: set(char *str) {
  30. delete[] s1;
  31. s1 = new char[strlen(str) + 1];
  32. strcpy(s1, str);
  33. }
  34. void STR::delsame() {
  35. int len = strlen(s1);
  36. if (len == 0) return;
  37. int k = 0;
  38. s2[k++] = s1[0];
  39. for (int i = 1; i < len; ++i) {
  40. bool isDuplicate = false;
  41. for (int j = 0; j < k; ++j) {
  42. if (s1[i] == s2[j]) {
  43. isDuplicate = true;
  44. break;
  45. }
  46. }
  47. if (!isDuplicate) {
  48. s2[k++] = s1[i];
  49. }
  50. }
  51. s2[k] = '\0';
  52. }
  53. void STR:: show() {
  54. std::cout << "原串:s1=" << s1 << std::endl;
  55. std::cout << "新串:s2=" << s2 << std::endl;
  56. }
  57. STR:: ~STR() {
  58. delete[] s1;
  59. delete[] s2;
  60. }
  61. //主函数测试
  62. int main() {
  63. STR test;
  64. char str[100];
  65. std::cout << "输入字符串:";
  66. std::cout << "\n";
  67. std::cin.getline(str, 100);
  68. test.set(str);
  69. test.delsame();
  70. test.show();
  71. return 0;}