#include <iostream>
using namespace std;
#include <assert.h>
class String
{
public:
String(char*str="")
{
_size = strlen(str);
_capacity = _size + 1;
_str = new char[_capacity];
strcpy(_str, str);
}
~String()
{
if (_str)
{
delete[]_str;
_size = 0;
_capacity = 0;
_str = NULL;
}
}
void PushBack(char ch)
{
CheckCapacity(_size+2);
_str[_size] = ch;
_str[++_size] = '\0';
}
void PopBack()
{
assert(_size > 0);
--_size;
_str[_size] = '\0';
}
//
void Insert(size_t pos, char ch)
{
assert(pos <= _size);
CheckCapacity(_size+2);
size_t Index = _size;
while (Index >= pos)
{
_str[Index + 1] = _str[Index];
--Index;
}
_str[pos] = ch;
_size++;
}
//
void Insert(size_t pos, char*str)
{
assert(pos <= _size);
size_t Index = _size;
int length = strlen(str);
CheckCapacity(_size+1+length);
while (Index >= pos)
{
_str[Index + length] = _str[Index];
--Index;
}
for (int i = 0; i < length; ++i)
{
_str[pos + i] = str[i];
}
_size += length;
}
//
size_t Find_Ch(char ch)
{
size_t length = strlen(_str);
for (int i = 0; i < length; i++)
{
if (_str[i] == ch)
{
return i;
}
}
return -1;
}
//
size_t Find_Str(const char*sub)
{
size_t SrcSize = _size;
size_t SubSize = strlen(sub);
size_t SrcIndex = 0;
while (SrcIndex <=_size-SubSize)
{
size_t SubIndex = 0;
size_t begin = SrcIndex;
while (begin < SrcSize
&&SubIndex < SubSize
&&_str[begin] == sub[SubIndex])
{
begin++;
SubIndex++;
}
if (SubIndex == SubSize)
{
return SrcIndex;
}
SrcIndex++;
}
return -1;
}
void Erase(size_t pos)
{
assert(pos);
for (int i = pos; i < _size-1; ++i)
{
_str[i] = _str[i + 1];
}
_size--;
_str[_size] = '\0';
}
String &operator+=( const String& s)
{
this->Insert(_size, s._str);
return *this;
}
char*CStr()
{
return _str;
}
private:
void CheckCapacity(int NeedSize)
{
if (NeedSize >= _capacity)
{
_capacity = NeedSize>2 * _capacity ?NeedSize:2*_capacity;
_str = (char*)realloc(_str, _capacity);
}
}
private:
char*_str;
int _size;
int _capacity;
};