#ifndef _MYSTRING_H_
#define _MYSTRING_H_
#include <iostream>
class MyString
{
private:
int capacity;
int size;
char *s;
public:
MyString();
MyString(const char* str);
~MyString();
MyString(const MyString& str);
MyString&operator=(const MyString& str);
MyString&operator+=(const char c);
MyString&operator+=(const MyString& str);
MyString operator+(const MyString & str);
MyString&operator-=(const MyString& str);
MyString operator-(const MyString& str);
char operator[](int index);
friend std::ostream& operator<<(std::ostream& os,const MyString &str);
friend std::istream& operator>>(std::istream& is,MyString &str);
};
std::ostream& operator<<(std::ostream& os,const MyString &str);
std::istream& operator>>(std::istream& is,MyString &str);
#endif
#include "MyString.h"
#include <cstring>
MyString::MyString():capacity(15),size(0)
{
this->s = new char[capacity];
}
MyString::MyString(const char *str)
{
this->size = strlen(str);
this->capacity = this->size = 15 ? size + 1 : 15;
this->s = new char[this->capacity];
strcpy(this->s,str);
}
MyString::~MyString()
{
delete []this->s;
}
MyString::MyString(const MyString &str)
{
this->size = str.size;
this->capacity = str.capacity;
this->s = new char[this->capacity];
strcpy(this->s,str.s);
}
MyString &MyString::operator=(const MyString &str)
{
this->size = str.size;
this->capacity=str.capacity;
delete []this->s;
this->s = new char[this->capacity];
strcpy(this->s,str.s);
return *this;
}
MyString &MyString::operator+=(const char c)
{
if(this->size > this->capacity - 2)
{
this->capacity *= 2;
char *newStr = new char[this->capacity];
strcpy(newStr,this->s);
delete []this->s;
this->s = newStr;
}
this->s[this->size++] = c;
this->s[this->size] = '\0';
return *this;
}
MyString &MyString::operator+=(const MyString &str)
{
this->size += str.size;
if(this->size >= this->capacity)
{
this->capacity = this->size + 1;
char *newp = new char[this->capacity];
strcpy(newp,this->s);
delete []this->s;
//strcpy(this->s,newp);
this->s = newp;
}
strcat(this->s,str.s);
return *this;
}
MyString MyString::operator+(const MyString &str)
{
MyString s(*this);
s += str;
return s;
}
MyString &MyString::operator-=(const MyString &str)
{
char *dest = strstr(this->s,str.s);
while(dest != nullptr)
{
char* back = dest + str.size;
while(*dest != '\0')
{
*dest++ = *back++;
}
this->size -= str.size;
this->size = '\0';
dest = strstr(this->s,str.s);
}
return *this;
}
MyString MyString::operator-(const MyString &str)
{
MyString s(*this);
s -= str;
return s;
}
char MyString::operator[](int index)
{
return this->s[index];
}
std::ostream &operator<<(std::ostream &os, const MyString &str)
{
os<<str.s;
return os;
}
std::istream &operator>>(std::istream &is, MyString & str)
{
char c = 0;
while ((c = getchar()) != '\n')
{
str += c;
}
return is;
}