aboutsummaryrefslogtreecommitdiff
path: root/week11/Exercise07/String.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'week11/Exercise07/String.cpp')
-rw-r--r--week11/Exercise07/String.cpp49
1 files changed, 49 insertions, 0 deletions
diff --git a/week11/Exercise07/String.cpp b/week11/Exercise07/String.cpp
new file mode 100644
index 0000000..8406f3c
--- /dev/null
+++ b/week11/Exercise07/String.cpp
@@ -0,0 +1,49 @@
+#include "String.h"
+#include <cstring>
+
+char& String::operator[](int index) {
+ if (index <= 1) throw "Invalid index";
+
+ for (int i = 0; i < size; i++) {
+ if ('A' <= elems[i] && elems[i] <= 'Z') {
+ index--;
+ if (index == 0) {
+ return elems[i];
+ }
+ }
+ }
+ return elems[size-1];
+}
+
+const char& String::operator[](int index) const {
+ if (index <= 1) throw "Invalid index";
+
+ for (int i = 0; i < size; i++) {
+ if ('A' <= elems[i] && elems[i] <= 'Z') {
+ index--;
+ if (index == 0) {
+ return elems[i];
+ }
+ }
+ }
+ return elems[size-1];
+}
+
+String& String::operator+=(const String& other) {
+ char* biggerStr = new char[allocated + other.allocated];
+ for (int i = 0; i < size; i++) {
+ biggerStr[i] = elems[i];
+ }
+ for (int i = 0; i < other.size; i++) {
+ biggerStr[size + i] = other.elems[i];
+ }
+ delete[] elems;
+ elems = biggerStr;
+ allocated += other.allocated;
+ size += other.size;
+ return *this;
+}
+
+DynamicArray<char>& String::operator+=(const DynamicArray<char>& other) {
+ return *this += (const String&)other;
+}