-
Notifications
You must be signed in to change notification settings - Fork 0
/
String.cpp
executable file
·122 lines (94 loc) · 1.94 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include "String.h"
using namespace dstring;
wchar_t* expand(const wchar_t* ptr, size_t n)
{
auto p = new wchar_t[n];
wcscpy_s(p, n, ptr);
return p;
}
String::String()
: sz(0),
space{ 0 },
pStr{ new wchar_t[sz + 1]{ 0 } }
{
}
String::String(const wchar_t* s)
: sz(wcslen(s)),
space{ 0 },
pStr{ new wchar_t[sz + 1] }
{
wcscpy_s(pStr, sz + 1, s);
}
String::String(const String& s)
{
copy_from(s);
}
String::~String()
{
delete[] pStr;
}
String& String::operator=(const String& s)
{
if (this == &s)
return *this;
auto p = pStr;
copy_from(s);
delete[] p;
return *this;
}
String& String::operator+=(wchar_t c)
{
if (space == 0) {
auto n = sz + sz + 2; // double the allocation (+2 because of the terminating 0)
auto p = expand(pStr, n);
delete[] pStr;
pStr = p;
space = n - sz - 2;
}
else
{
--space;
}
pStr[sz] = c; // add "c" at end
pStr[++sz] = 0; // increase size and set terminator
return *this;
}
void String::copy_from(const String& x)
{
sz = x.sz;
pStr = expand(x.pStr, x.sz + 1);
space = 0;
}
String& dstring::operator+=(String& a, const String& b)
{
for (auto c = b.c_str(); c != b.c_str() + b.size(); ++c)
a += *c;
return a;
}
String dstring::operator+(const String& a, const String& b)
{
auto sum{ a };
sum += b;
return sum;
}
std::wostream& dstring::operator<<(std::wostream& os, const String& s)
{
return os << s.c_str();
}
std::wistream& dstring::operator>>(std::wistream& is, String& s)
{
s = L""; // clear the target string
is >> std::ws; // skip whitespace
wchar_t ch;
while (is.get(ch) && !isspace(ch))
s += ch;
return is;
}
bool dstring::operator<(const String& a, const String& b)
{
return _wcsicmp(a.c_str(), b.c_str()) < 0 ? true : false;
}
bool dstring::operator>(const String& a, const String& b)
{
return _wcsicmp(a.c_str(), b.c_str()) > 0 ? true : false;
}