Website Summary Files Commits Branches @commit @diff @stats
path: root / Week07 / Exercise01 / String.cpp
diff options
context:
space:
mode:
Commit945f7e67d6ca8047c961457786fac5e2d9a13d82 (patch)
Author
 Syndamia <kamen@syndamia.com>
2026-04-03 18:17:51 +0300
Committer
 Syndamia <kamen@syndamia.com>
2026-04-03 18:17:51 +0300
Files5c6b23aaee4eb653f9c461d7303edcd31d697f10 /Week07/Exercise01/String.cpp
oop-2025-solutions-945f7e67d6ca8047c961457786fac5e2d9a13d82.tar
oop-2025-solutions-945f7e67d6ca8047c961457786fac5e2d9a13d82.tar.gz
oop-2025-solutions-945f7e67d6ca8047c961457786fac5e2d9a13d82.zip
Parent8f162cde46a34d04e3a8a655067ee5174258e249 (diff)
feat(Week07): Add solutions
1 files changed, 98 insertions, 0 deletions
-rw-r--r--Week07/Exercise01/String.cpp98
diff --git a/Week07/Exercise01/String.cpp b/Week07/Exercise01/String.cpp
new file mode 100644
index 0000000..8272658
--- /dev/null
+++ b/Week07/Exercise01/String.cpp
@@ -0,0 +1,98 @@
+#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);
+}
+
+void String::resize() {
+ allocated = allocated == 0 ? 8 : allocated * 2;
+ char* strLarger = new char[allocated];
+
+ memcpy(strLarger, str, length);
+ strLarger[length] = '\0';
+
+ delete[] str;
+ str = strLarger;
+}
+
+String::String() {
+ str = nullptr;
+ allocated = 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);
+}
+
+void String::Clear() {
+ free();
+ str = nullptr;
+ length = allocated = 0;
+}
+
+void String::AppendChar(char c) {
+ if (length + 1 >= allocated)
+ resize();
+ str[length++] = c;
+ str[length] = '\0';
+}
+
+bool String::EqualTo(const String& other) const {
+ return strcmp(str, other.str) == 0;
+}
+
+const char* String::GetStr() const {
+ return str;
+}
+
+unsigned String::GetLength() const {
+ return length;
+}