#include <iostream>
#include <assert.h>
using namespace std;
class String
{
public:
String(char* str = "")
{
_size = strlen(str);
_capacity = _size + 1;
_str = new char[_capacity];
strcpy(_str, str);
}
//String(const String& s)
// :_str(new char[strlen(s._str)+1])
//{
// strcpy(_str, s._str);
//}
String(const String& s)
{
String tmp(s._str);
swap(_str, tmp._str);
}
~String()
{
if(_str)
{
delete[] _str;
_capacity = 0;
_size = 0;
_str = NULL;
}
}
String& operator=(const String& s)
{
if(this != &s)
{
/*delete[] _str;
_str = new char[strlen(s._str)+1];
strcpy(_str, s._str);*/
char* tmp = new char[strlen(s._str)+1];
strcpy(tmp, s._str);
delete[] _str;
_str = tmp;
}
}
char& operator[](size_t index)
{
return _str[index];
}
String& operator+=(const String& s)
{
this->Insert(_size, s._str);
return *this;
}
bool operator==(const String& s)
{
int i = 0;
while(_str[i] == s._str[i])
{
++i;
}
if(i == _size)
{
return true;
}
return false;
}
bool operator>(const String& s)
{
int i = 0;
while(_str[i] == s._str[i])
{
++i;
}
if(_str[i] > s._str[i])
{
return true;
}
return false;
}
bool operator>=(const String& s)
{
return *this == s || *this > s;
}
bool operator<(const String& s)
{
return !(*this >= s);
}
bool operator<=(const String& s)
{
return !(*this > s);
}
void PushBack(char ch)
{
//_CheckCapacity(_size + 2);
//_str[_size] = ch;
//_str[++_size] = '\0';
Insert(_size, ch);
}
void PopBack()
{
assert(_size > 0);
--_size;
_str[_size] = '\0';
}
void Insert(size_t pos, char ch)//在pos位置插入一个字符
{
assert(pos <= _size);
size_t index = _size;
while(index >= pos)
{
_str[index+1] = _str[index];
--index;
}
_str[pos] = ch;
++_size;
}
//在pos位置插入一个字符串
void Insert(size_t pos, const char* str)
{
assert(pos <= _size);
//1.增容
size_t size = strlen(str);
_CheckCapacity(_size + 1 + size);
//2.挪动数据
size_t index = _size;
while(index >= pos)
{
_str[index+size] = _str[index];
--index;
}
//3.插入str
for(size_t i = 0; i < size; ++i)
{
_str[pos++] = str[i];
}
_size += size;
}
//查找字符
int Find(char ch)
{
for(size_t i = 0; i < _size; ++i)
{
if(i == _str[i])
{
return i;
}
}
return -1;
}
//查找子串
int Find(const char* sub)
{
size_t subSize = strlen(sub);//子串大小
size_t srcIndex = 0;//源字符串下标
while(srcIndex <= _size - subSize)
{
size_t subIndex = 0;
size_t begin = srcIndex;
while(subIndex < subSize
&& begin < _size
&& _str[begin] == sub[subIndex])
{
++begin;
++subIndex;
}
if(subIndex == subSize)
{
return srcIndex;
}
++srcIndex;
}
return -1;
}
//删除pos位置的值
void Erase(size_t pos)
{
}
char* C_Str()
{
return _str;
}
private:
void _CheckCapacity(size_t NeedSize)
{
if(NeedSize >= _capacity)
{
//_capacity *= 2;
_capacity = NeedSize > 2*_capacity ? NeedSize : 2*_capacity;
_str = (char*)realloc(_str, _capacity);
}
}
private:
char* _str;
size_t _size;//字符个数
size_t _capacity;//容量空间
};
【C++】String类
最新推荐文章于 2022-04-22 16:40:34 发布