类实现C++string部分功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <cstring>

class String{
public:
String(char *s = NULL) {
if (s != NULL) {
string = new char(strlen(s) + 1);
if (string) {
string = strcpy(string, s);
}
}
};

size_t length();
String operator+(String str);
String operator+(char *str);
String operator=(String str);
char operator[](int index);
bool isempty();
friend ostream& operator <<(ostream &out,const String &str);
char* insert(size_t index,const char* str);
char* insert(size_t index,const String str);

private:
char* string;

};

char String::operator[](int index) {
return this -> string[index];
}

ostream& operator <<(ostream &out,String &str) {
for (int i = 0; i < str.length(); i++) {
out << str[i];
}
return out;
}

String String::operator=(String str) {
String S(this -> string = str.string);
return S;
}

bool String::isempty() {
if (this -> string) {
return false;
} else {
return true;
}
}

size_t String::length() {
return strlen(this -> string);
}

String String::operator+(String str) {
String S(strcat(this -> string, str.string));
return S;
}

String String::operator+(char *str) {
String S(strcat(this -> string, str));
return S;
}

char* String::insert(size_t index,const char *str) {
char *s = new char(strlen(string) + 100);
strncpy(s, this -> string, index);
strcpy(s + index, str);
strcpy(s + index + strlen(str),this -> string + index);
return s;
}

char* String::insert(size_t index, String str) {
char *s = new char(strlen(this -> string) + 100);
strncpy(s, this -> string, index);
strcpy(s + index, str.string);
strcpy(s + index + strlen(str.string), this -> string + index);
return s;
}
script>