-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathString.cpp
More file actions
129 lines (110 loc) · 2.09 KB
/
String.cpp
File metadata and controls
129 lines (110 loc) · 2.09 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <cstdlib>
#include <cstring>
#include "String.h"
String::String() {
cstr = new char;
cstr[0] = '\0';
size = max = 0;
}
String::String(const char *s) {
max = size = strlen(s);
cstr = new char[size+1];
strcpy(cstr, s);
}
String::String(char c) {
max = size = 1;
cstr = new char[size+1];
cstr[0] = c;
cstr[1] = '\0';
}
String::String(const String &s) {
max = size = s.size;
cstr = new char[size+1];
strcpy(cstr, s.cstr);
}
String::~String() {
delete [] cstr;
}
String String::substring(size_t pos, size_t len) const {
char buf[len + 1];
strncpy(buf, &cstr[pos], len);
return String(buf);
}
char String::operator[](size_t i) const {
return cstr[i];
}
bool String::operator==(const String &s) const {
return !strcmp(cstr, s.cstr);
}
const char* String::cstring() const {
return cstr;
}
size_t String::len() {
return size;
}
void String::shrink() {
if (max > size) {
char *buf = new char[size+1];
strcpy(buf, cstr);
delete [] cstr;
cstr = buf;
max = size;
}
}
void String::grow() {
if(cstr == NULL) {
max = 1;
size = 0;
cstr = new char[max + 1];
} else {
char *buf = new char[(max*=GROW)+1];
strcpy(buf, cstr);
delete [] cstr;
cstr = buf;
}
}
const String& String::operator=(const String& s) {
delete [] cstr;
size = max = s.size;
cstr = new char[size + 1];
strcpy(cstr, s.cstr);
return *this;
}
std::ostream& operator<<(std::ostream &os, const String &s) {
return os << s.cstr ;
}
std::istream& operator>>(std::istream &is, String &s) {
char delims[] = {' ', '\n', '\t'};
char c;
int i = 0;
// eat up delim chars
while (is.get(c)) {
if (c != delims[0] && c != delims[1] && c != delims[2]) {
is.putback(c);
break;
}
}
while (is.get(c)) {
if (i == s.max) {
s.grow();
s.cstr[i] = '\0' ;
}
if (c != delims[0] && c != delims[1] && c != delims[2]) {
s.cstr[i] = c;
}
else {
is.putback(c);
break;
}
i++;
}
s.size = i;
s.cstr[i] = '\0' ;
return is;
}
String operator+(const String &a, const String &b) {
char *sum = new char[a.size + b.size + 1];
strcpy(sum, a.cstr);
strcat(sum, b.cstr);
return String(sum);
}