CSCE 121 Introduction to Program Design and Concepts | MyString.cpp
#include "MyString.h"
#include
using std::ostream;
using std::cout, std::endl;
MyString::MyString(const MyString& string1) : size1(0), capacity1(
...
CSCE 121 Introduction to Program Design and Concepts | MyString.cpp
#include "MyString.h"
#include
using std::ostream;
using std::cout, std::endl;
MyString::MyString(const MyString& string1) : size1(0), capacity1(1), str(nullptr)
{
this->size1 = string1.size();
this->capacity1 = string1.capacity();
this->str = new char[this->capacity1];
for (size_t i = 0; i < this->size1; i++) {
this->str[i] = string1.str[i];
}
this->str[size1] = '\0';
}
MyString::MyString() : size1(0), capacity1(1), str(nullptr)
{
this->size1 = 0;
this->capacity1 = 1;
this->str = new char[1];
this->str[0] = '\0';
}
MyString::MyString(const char* val) : size1(0), capacity1(1), str(nullptr)
{
this->size1 = 0;
this->capacity1 = 1;
this->str = nullptr;
if (val == nullptr) {
this->size1 = 0;
this->capacity1 = 1;
this->str = new char[this->capacity1];
this->str[0] = '\0';
} else {
int i = 0;
size_t newsize = 0;
while (val[i] != '\0') {
newsize += 1;
i += 1;
}
this->size1 = newsize;
this->capacity1 = newsize + 1;
this->str = new char[this->capacity1];
for (size_t j = 0; j < this->size1; j++) {
this->str[j] = val[j];
}
this->str[this->size1] = '\0';
}
MyString::~MyString() { delete[] str; }
void MyString::resize(size_t n) {
this->capacity1 = n;
char* temp = new char[n];
int index = 0;
while (this->str[index] != '\0') {
temp[index] = str[index];
index+=1;
}
temp[index] = '\0';
delete[] this->str;
this->str = temp;
this->capacity1 = n;
}
const char& MyString::at (size_t pos) const {
if(pos < this->length()) {
return this->str[pos];
} else {
throw std::out_of_range("Invalid position");
}
}
size_t MyString::capacity() const {
return this->capacity1;
}
size_t MyString::length() const {
return this->size1;
}
size_t MyString::size() const {
return this->size1;
}
[Show More]