-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.cpp
More file actions
77 lines (62 loc) · 1.43 KB
/
string.cpp
File metadata and controls
77 lines (62 loc) · 1.43 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
#include <cstring> // strlen, strcpy
#include <iostream>
using namespace std;
struct String {
/* Constructors */
String(const char *str = "") {
int len = strlen(str);
//We can omit pointer to this here
this->size_ = len;
this->str_ = new char[len];
strcpy(this->str_, str);
}
String(size_t n, char c) {
this->size_ = n;
this->str_ = new char[n + 1];
for (int i = 0; i < n; i++) {
this->str_[i] = c;
}
}
/* Destructor */
~String() {
delete [] str_;
}
/* Fields */
size_t size_;
char *str_;
/* Methods */
size_t size() {
return size_;
}
char &at(size_t idx) {
return str_[idx];
}
const char *c_str() {
return str_;
}
int compare(String &str) {
return strcmp(this->str_, str.str_);
}
void append(String &str) {
int newSize = size_ + str.size_;
char * newString = new char[newSize + 1];
strcpy(newString, str_);
strcpy(newString + size_, str.str_);
delete [] str_;
size_ = newSize;
str_ = newString;
}
};
main() {
char a[] = "Hello,";
char b[] = " World!";
String s(a);
String s1(b);
cout << s.size() << endl;
cout << s.at(1) << endl;
cout << s.c_str() << endl;
cout << s.compare(s1) << endl;
s.append(s1);
cout << s.c_str() << endl;
cout << s.size() << endl;
}