1 #include <iostream>
2 #include <cstring>
3 using namespace std;
4
5 class String {
6 public:
7 // 默认构造函数
8 String(const char* str = NULL);
9 // 复制构造函数
10 String(const String &str);
11 // 析构函数
12 ~String();
13 // 字符串连接
14 String operator+(const String & str);
15 // 字符串赋值
16 String & operator=(const String &str);
17 // 字符串赋值
18 String & operator=(const char* str);
19 // 判断是否字符串相等
20 bool operator==(const String &str);
21 // 获取字符串长度
22 int length();
23 // 求子字符串[start,start+n-1]
24 String substr(int start, int n);
25 // 重载输出
26 friend ostream & operator<<(ostream &o,const String &str);
27 private:
28 char* data;
29 int size;
30 };
31
32 // 构造函数
33 String::String(const char *str) {
34 if(str == NULL){
35 data = new char[1];
36 data[0] = '\0';
37 size = 0;
38 }
39 else{
40 size = strlen(str);
41 data = new char[size+1];
42 strcpy(data,str);
43 }
44 }
45
46 // 复制构造函数
47 String::String(const String &str) {
48 size = str.size;
49 data = new char[size+1];
50 strcpy(data,str.data);
51 }
52
53 // 析构函数
54 String::~String(){
55 delete[] data;
56 }
57
58 // 字符串连接
59 String String::operator+(const String &str) {
60 String newStr;
61 //释放原有空间
62 delete[] newStr.data;
63 newStr.size = size + str.size;
64 newStr.data = new char[newStr.size+1];
65 strcpy(newStr.data,data);
66 strcpy(newStr.data+size,str.data);
67 return newStr;
68 }
69
70 // 字符串赋值
71 String & String::operator=(const String &str) {
72 if(data == str.data){
73 return *this;
74 }
75 delete [] data;
76 size = str.size;
77 data = new char[size+1];
78 strcpy(data,str.data);
79 return *this;
80 }
81
82 // 字符串赋值
83 String& String::operator=(const char* str) {
84 if(data == str){
85 return *this;
86 }
87 delete[] data;
88 size = strlen(str);
89 data = new char[size+1];
90 strcpy(data,str);
91 return *this;
92 }
93
94 // 判断是否字符串相等
95 bool String::operator==(const String &str) {
96 return strcmp(data,str.data) == 0;
97 }
98
99 // 获取字符串长度
100 int String::length(){
101 return size;
102 }
103
104 // 求子字符串[start,start+n-1]
105 String String::substr(int start, int n) {
106 String newStr;
107 // 释放原有内存
108 delete [] newStr.data;
109 // 重新申请内存
110 newStr.data = new char[n+1];
111 for(int i = 0;i < n;++i){
112 newStr.data[i] = data[start+i];
113 }
114 newStr.data[n] = '\0';
115 newStr.size = n;
116
117 return newStr;
118 }