Website Summary Files Commits Branches @commit @diff @stats
path: root / Week05 / Exercise02 / String.cpp
blob: e2b082dfda26e4c364a0d21fdb4c1b281ad0ce3e (plain) (blame)
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
#include "String.h"
#include <cstring>

void String::free() {
	delete[] str;
}

void String::copyFrom(const String& other) {
	length = other.length;

	// Не забравяме за терминиращата нула
	str = new char[length + 1];
	strncpy(str, other.str, length + 1);
}

String::String() {
	str = nullptr;
	length = 0;
}

String::~String() {
	free();
}

String::String(const String& other) {
	copyFrom(other);
}

String& String::operator=(const String& other) {
	if (this != &other) {
		free();
		copyFrom(other);
	}
	return *this;
}

String::String(String&& other) {
	str = other.str;
	length = other.length;

	other.str = nullptr;
	other.length = 0;
}

String& String::operator=(String&& other) {
	if (this != &other) {
		free();

		str = other.str;
		length = other.length;

		other.str = nullptr;
		other.length = 0;
	}
	return *this;
}

String::String(const char* str) {
	length = strlen(str);
	this->str = new char[length + 1];
	strncpy(this->str, str, length + 1);
}

String String::Substring(unsigned startIndex, unsigned length) const {
	String result;
	if (startIndex >= this->length) {
		return result;
	}

	if (startIndex + length >= this->length) {
		length = this->length - startIndex;
	}

	result.length = length;
	result.str = new char[length + 1];
	strncpy(result.str, str, length);
	result.str[length + 1] = '\0';

	return result;
}

void String::Concat(const String& end) {
	char* newStr = new char[length + end.length + 1];
	strncpy(newStr, str, length);
	strncpy(newStr + length, end.str, end.length + 1);

	delete[] str;
	str = newStr;
	length += end.length;
}

unsigned String::CountWords() const {
	unsigned words = 0;
	bool prevBlank = true;

	for (const char* s = str; *s != '\0'; ++s) {
		if (prevBlank && *s != ' ')
			++words;
		prevBlank = *s == ' ';
	}

	return words;
}