1 /*
2 *
htwg_string.cpp
3 *
4 * Stark vereinfachte String-Klasse.
5 *
6 * Autor: H.Drachenfels
7 * Erstellt am: 30.5.2024
8 */
9 #include "htwg_string.h"
10 using namespace htwg;
11
12 #include <cstring>
13
14 // Konstruktoren
15 string::string()
16 {
17 this->n = 0;
18 this->s = new char[1];
19 *this->s = '\0';
20 }
21
22 string::string(const char* s)
23 {
24 this->n = std::strlen(s);
25 this->s = new char[this->n + 1];
26 std::strcpy(this->s, s);
27 }
28
29 // Rule-of-five-Memberfunktionen (Destruktor und Copy/Move)
30 string::~string()
31 {
32 delete[] this->s;
33 }
34
35 string::string(const string& that)
36 {
37 this->n = that.n;
38 this->s = new char[this->n + 1];
39 std::strcpy(this->s, that.s);
40 }
41
42 string::string(string&& that) : n(that.n), s(that.s)
43 {
44 that.n = 0;
45 that.s = nullptr;
46 }
47
48 string& string::operator=(const string& that)
49 {
50 if (this != &that)
51 {
52 delete[] this->s;
53 this->n = that.n;
54 this->s = new char[this->n + 1];
55 std::strcpy(this->s, that.s);
56 }
57
58 return *this;
59 }
60
61 string& string::operator=(string&& that)
62 {
63 if (this != &that)
64 {
65 delete[] this->s;
66 this->n = that.n;
67 this->s = that.s;
68 that.n = 0;
69 that.s = nullptr;
70 }
71
72 return *this;
73 }
74
75 // String-Konkatenation
76 string& string::operator+=(const string& that)
77 {
78 std::size_t m = this->n + that.n;
79 char *t = new char[m + 1];
80 std::strcpy(t, this->s);
81 std::strcpy(t + this->n, that.s);
82 delete[] this->s;
83 this->n = m;
84 this->s = t;
85
86 return *this;
87 }
88
89 // Vergleich(e)
90 namespace htwg
91 {
92 bool operator<(const string& lhs, const string& rhs)
93 {
94 return std::strcmp(lhs.s, rhs.s) < 0;
95 }
96 }
97
98 // Datenabfragen
99 const char* string::c_str() const
100 {
101 return this->s;
102 }
103
104 std::size_t string::length() const
105 {
106 return this->n;
107 }
108