You are on page 1of 3

#ifndef myString_h

#define myString_h

#include <iostream>
#include <cstring>
using namespace std;

class MyString {
private:
char* pString;
public:
MyString();
MyString(const char* str);
MyString(const MyString& other);
~MyString();

bool operator==(const MyString& other) const;


MyString& operator+=(const MyString& other);
MyString& operator=(const MyString& other);

friend std::ostream& operator<<(std::ostream& os, const MyString& str);

};
#endif

#include "myString.h"

MyString::MyString() {
this->pString = nullptr;
};

MyString::MyString(const char* str) {


int length = 0;
while (str[length] != '\0') {
++length;
}
this->pString = new char[length + 1];
for (int i = 0; i < length; ++i) {
this->pString[i] = str[i];
}
this->pString[length] = '\0';
};

MyString::MyString(const MyString& other) {


if (this != &other) {
int length = 0;
while (other.pString[length] != '\0') {
++length;
}

this->pString = new char[length + 1];


for (int i = 0; i < length; ++i) {
this->pString[i] = other.pString[i];
}
this->pString[length] = '\0';
}
}

MyString::~MyString() {
delete[] this->pString;
};

bool MyString::operator==(const MyString& other) const {


int i = 0;
while (this->pString[i] != '\0' && other.pString[i] != '\0') {
if (this->pString[i] != other.pString[i]) {
return false;
}
i++;
}
return true;
};

MyString& MyString::operator+=(const MyString& other) {


int length1 = 0;
while (this->pString[length1] != '\0') {
++length1;
}
int length2 = 0;
while (other.pString[length2] != '\0') {
++length2;
}

char* result = new char[length1 + length2 + 1];


for (int i = 0; i < length1; i++) {
result[i] = this->pString[i];
}
for (int j = 0; j < length1 + length2; j++) {
result[length1 + j] = other.pString[j];
}

result[length1 + length2] = '\0';


delete[] this->pString;
this->pString = result;

return *this;
};

MyString& MyString::operator=(const MyString& other) {


if (this != &other) {
int length = 0;
while (other.pString[length] != '\0') {
++length;
}
char* tmp = new char[length + 1];
for (int i = 0; i < length; ++i) {
tmp[i] = other.pString[i];
}
tmp[length] = '\0';
delete[] this->pString;
this->pString = tmp;
}
return *this;
};

ostream& operator<<(std::ostream& os, const MyString& str) {


int i = 0;
while (str.pString[i] != '\0') {
os << str.pString[i++];
}
return os;
};
#include "myString.h"

int main() {

MyString s1;

MyString s2("Hello");

cout << "s2: " << s2 << endl;

if (s2 == "Hello") {
cout << "s2 is equal to \"Hello\"" << endl;
}
else {
cout << "s2 is not equal to \"Hello\"" << endl;
}

MyString s3 = s2;
s3 += " World";
cout << "s3 after concatenation: " << s3 << endl;

s1 = s3;
cout << "s1 after assignment: " << s1 << endl;

return 0;
}

You might also like