aboutsummaryrefslogtreecommitdiff
path: root/week11/Exercise07/String.cpp
blob: 8406f3c8f2a1bec67d4d7ba99392503fb25ce3e0 (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
#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;
}