主要内容:模拟实现String类的默认成员函数,增删查改,及各类运算符重载等。
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<assert.h>
using namespace std;
class String
{
public:
String(const char* str = "")
:_str(new char[strlen(str) + 1])
, _size(strlen(str))
, _capacity(_size)
{
strcpy(_str, str);
}
void show()
{
cout << "_str:" << _str << endl;
cout << "_size:" << _size << endl;
cout << "_capcity" << _capacity << endl;
}
void Swap(String& s)
{
if (s._str != _str)
{
swap(_str, s._str);
swap(_size, s._size);
swap(_capacity, s._capacity);
}
}
String(const String& s)
{
String s1(s._str);
Swap(s1);
}
String& operator=(const String &s)
{
if (_str != s._str)
{
String tmp(s._str);
Swap(tmp);
}
return *this;
}
~String()
{
delete[] _str;
_str = NULL;
}
const char* c_str()
{
return _str;
}
void Expand(size_t n)
{
_capacity += n;
char *tmp = new char[_capacity + 1];
strcpy(tmp, _str);
swap(tmp, _str);
delete[] tmp;
}
void PushBack(char ch)
{
Insert(_size, ch);
}
void PopBack()
{
Erase(_size - 1, 1);
}
void Insert(size_t pos, char ch)
{
assert(pos <= _size);
if (_size + 1 >= _capacity)
{
Expand(5);
}
memmove(_str + pos + 1, _str + pos, _size - pos + 1);
_str[pos] = ch;
_size++;
}
void Insert(size_t pos, const char* str)
{
assert(pos <= _size);
if (_size + strlen(str) >= _capacity)
{
Expand(strlen(str));
}
memmove(_str + pos + strlen(str), _str + pos, _size - pos + 1);
strncpy(_str + pos, str, strlen(str));
_size += strlen(str);
}
void Erase(size_t pos, size_t n = 1)
{
assert(pos < _size);
assert(n <= _size);
if (_size == 0)
{
cout << "the string is empty!!" << endl;
return;
}
memmove(_str + pos, _str + pos + n, _size - n + 1);
_size -= n;
}
size_t Find(char ch)
{
char *tmp = strchr(_str, ch);
if (tmp == NULL)
{
printf("'ch' is not in this string!!\n");
return -1;
}
return tmp - _str;
}
size_t Find(const char* str)
{
assert(str);
char *tmp = strstr(_str, str);
if (tmp)
{
return tmp - _str;
}
return -1;
}
String operator+(char ch)
{
String s1(_str);
s1.PushBack(ch);
return s1;
}
String& operator+=(char ch)
{
PushBack(ch);
return *this;
}
String operator+(const char* str)
{
String s1(_str);
s1.Insert(strlen(_str), str);
return s1;
}
String& operator+=(const char* str)
{
Insert(strlen(_str), str);
return *this;
}
bool operator>(const String& s)
{
if (strcmp(_str, s._str) > 0)
{
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);
}
bool operator==(const String& s)
{
if (strcmp(_str, s._str) == 0)
{
return true;
}
return false;
}
bool operator!=(const String& s)
{
return !(*this == s);
}
private:
char* _str;
size_t _size;
size_t _capacity;
};