-
Notifications
You must be signed in to change notification settings - Fork 0
/
string.cpp
101 lines (86 loc) · 2.06 KB
/
string.cpp
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
/*
* string.cpp
* Untitled
*
* Created by Ellie on 5/09/10.
* Copyright 2010 Ellie. All rights reserved.
*
*/
#include <cstring>
#include "string.h"
String::String(const char *s) {
if (s) {
m_length = strlen(s);
m_size = 1 + m_length;
m_cstring = new char[m_size];
strcpy(m_cstring, s);
}
else {
m_length = 0;
m_size = 1;
m_cstring = new char[m_size];
m_cstring[0] = '\0';
}
}
String::String(const String &s) {
m_length = s.length();
m_size = 1 + m_length;
m_cstring = new char[m_size];
strcpy(m_cstring, s);
}
String::String() {
m_length = 0;
m_size = 1;
m_cstring = new char[m_size];
m_cstring[0] = '\0';
}
String::~String() {
delete[] m_cstring;
}
bool String::operator==(const String &other) const {
return strcmp(m_cstring, other) == 0;
}
bool String::operator<(const String &other) const {
return strcmp(m_cstring, other) < 0;
}
bool String::operator>(const String &other) const {
return strcmp(m_cstring, other) > 0;
}
String &String::operator=(const String &other) {
if (this == &other) return *this;
if (other.length() >= m_size) {
delete[] m_cstring;
m_length = other.length();
m_size = 1 + m_length;
m_cstring = new char[m_size];
strcpy(m_cstring, other);
}
else {
m_length = other.length();
strcpy(m_cstring, other);
}
return *this;
}
String &String::operator+=(const String &other) {
m_length += other.length();
if (m_size <= m_length) {
m_size = 1 + m_length;
char *tmp = new char[m_size];
strcpy(tmp, m_cstring);
strcat(tmp, other);
delete[] m_cstring;
m_cstring = tmp;
}
else {
strcat(m_cstring, other);
}
return *this;
}
String operator+(const String &left, const String &right) {
char *tmp = new char[1 + left.length() + right.length()];
strcpy(tmp, left);
strcat(tmp, right);
String result(tmp);
delete[] tmp;
return result;
}