-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
String.h
130 lines (105 loc) · 2.03 KB
/
String.h
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
130
#pragma once
#include <iostream>
using namespace std;
class String
{
char* text;
unsigned int length;
unsigned int capacity;
public:
String(const char* text, unsigned int capacity = 80)
{
Initialize(text);
}
explicit operator int() { return 1; }
// ïðèìåð ïåðåãðóçêè îïåðàòîðà èíäåêñàöèè []
char& operator[](unsigned int index)
{
if (index >= length || index < 0) throw "OOPS!";
else return text[index];
}
String()
{
Initialize("");
}
String(unsigned int capacity)
{
Initialize("", capacity);
}
String(const String& original)
{
Initialize(original.text, original.capacity);
}
~String()
{
delete[] text;
}
// ãåòòåðû-ñåòòåðû
const char* GetString() const
{
return text;
}
void SetString(const char* text)
{
length = strlen(text);
if (length >= capacity)
{
delete[] this->text;
capacity = length + 20;
this->text = new char[capacity];
}
strcpy_s(this->text, length + 1, text);
}
int GetLength() const
{
return length;
}
// ìåòîäà SetLength íå äîëæíî áûòü!
int GetCapacity() const
{
return capacity;
}
void Clear()
{
text[0] = '\0';
length = 0;
}
void ShrinkToFit()
{
if (length + 1 == capacity)
{
return;
}
capacity = length + 1;
char* temp = new char[capacity];
strcpy_s(temp, capacity, text);
delete[] text;
text = temp;
}
private:
void Initialize(const char* str, int capacity = 80) {
length = strlen(str);
this->capacity = (capacity > length) ? capacity : length + 20;
this->text = new char[this->capacity];
strcpy_s(this->text, length + 1, str);
}
public:
String& operator()(const char* value)
{
// î÷èñòêà ïàìÿòè îò ñòàðîé ñòðîêè
if (text != nullptr) delete[] text;
// ïîäñ÷¸ò äëèíû ïåðåäàííîé ñòðîêè +1 äëÿ ñèìâîëà ñ êîäîì 0
int l = strlen(value) + 1;
text = new char[l];
strcpy_s(text, l, value);
capacity = l;
length = l - 1;
return *this;
}
//friend ostream& operator <<(ostream& os, const String& obj);
};
ostream& operator <<(ostream& os, const String& obj)
{
cout << obj.GetString() << "\n";
return os;
}