C++string类模拟实现
上篇博客对string类进行了简单的介绍,大家只要能够正常使用就可以了。
既然学了string类,那模拟实现一下string类。
1.头文件
#include<iostream>
#include<assert.h>
using namespace std;
class String
{
public:
//构造
String(const char* str = "");
//拷贝构造
String(const String& s);
//析构
~String();
//赋值重载
//传统写法
String& operator=(const String& s);
//现代写法
String& operator=(String s);
//iterator
typedef char* iterator;
iterator begin();
iterator end();
//Modify
void push_back(char c);
void append(const char* str);
String& operator+=(char c);
String& operator+=(const char* str);
void clear();
void swap(String& s);
const char* c_str()const;
// capacity
size_t size()const;
size_t capacity()const;
bool empty()const;
void resize(size_t n, char c = '\0');
void reserve(size_t n);
//access
char& operator[](size_t index);
const char& operator[](size_t index)const;
//relational operators
bool operator<(const String& s);
bool operator<=(const String& s);
bool operator>(const String& s);
bool operator>=(const String& s);
bool operator==(const String& s);
bool operator!=(const String& s);
// 返回c在string中第一次出现的位置
size_t find(char c, size_t pos = 0) const;
// 返回子串s在string中第一次出现的位置
size_t find(const char* s, size_t pos = 0) const;
// 在pos位置上插入字符c/字符串str,并返回该字符的位置
String& insert(size_t pos, char c);
String& insert(size_t pos, const char* str);
// 删除pos到len位置的字符
String& erase(size_t pos, size_t len = npos);
private:
char* _str;
size_t _size;
size_t _capacity;
const static size_t npos = -1;
};
2.默认成员函数
2.1构造函数
//构造函数
String::String(const char* str)
{
//这里特殊处理一下,使_capacity = _size;下面push_back有解释
_size = strlen(str);
_capacity = _size;
_str = new char[_capacity + 1];
strcpy(_str, str);
}
2.2拷贝构造函数
2.2.1传统写法
//拷贝构造传统写法
String::String(const String& s)
{
_size = s._size;
_capacity = s._capacity;
_str = new char[_capacity + 1];
//写法1,自己一个个赋值
//size_t i = 0;
//for ( i; i < s._capacity; ++i)
//{
// _str[i] = s._str[i];
//}
//_str[i] = '\0';
//写法2,使用C库函数拷贝
strcpy(_str, s._str);
}
2.2.2现代写法
void String::swap(String& s)
{
std::swap(_str, s._str);
std::swap(_size, s._size);
std::swap(_capacity, s._capacity);
}
//拷贝构造 现代写法
String::String(const String& s)
:_str(nullptr)
,_size(0)
,_capacity(0)
{
String tmp(s._str);
//this->swap(tmp);
//成员函数,成员变量前面自动加this
swap(tmp);
}
注意我们自己实现了一个交换函数。
下面是库的。如果直接使用库里的,就会调用一个拷贝构造,两个赋值重载,太影响效率。
2.3赋值重载
2.3.1传统写法
//赋值重载 传统写法
String& String::operator=(const String& s)
{
if (this != &s)
{
delete[] _str;
_size = s._size;
_capacity = s._capacity;
_str = new char[s._capacity + 1];
//写法1
//size_t i = 0;
//for (i; i < s._capacity; ++i)
//{
// _str[i] = s._str[i];
//}
//_str[i] = '\0';
//写法2
strcpy(_str, s._str);
}
return *this;
}
2.3.2现代写法
//赋值重载 现代写法1
String& String::operator=(const String& s)
{
if (this != &s)
{
String tmp(s);
swap(tmp);
}
return *this;
}
赋值重载现代写法1和拷贝构造现代写法是一样的。
//赋值重载 现代写法2
String& String::operator=(String s)
{
swap(s);
return *this;
}
2.4析构函数
//析构
String::~String()
{
delete[] _str;
_str = nullptr;
_size = _capacity = 0;
}
3.iterator操作
//声明
typedef char* iterator;
iterator begin();
iterator end();
3.1begin
String::iterator String::begin()
{
return &_str[0];
}
3.2end
String::iterator String::end()
{
return &_str[_size];
}
4.access操作
//声明
char& operator[](size_t index);
const char& operator[](size_t index)const;
因为operator[]函数返回值可读可写,因此需要实现非const,const类型的。
char& String::operator[](size_t index)
{
assert(index < _size);
return _str[index];
}
const char& String::operator[](size_t index)const
{
assert(index < _size);
return _str[index];
}
5.capacity操作
//声明
size_t size()const;
size_t capacity()const;
bool empty()const;
void resize(size_t n, char c = '\0');
void reserve(size_t n);
5.1size
size_t String::size()const
{
return _size;
}
5.2capacity
size_t String::size()const
{
return _capacity;
}
5.3empty
bool String::empty()const
{
return _size == 0;
}
5.4reverse
void String::reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}
因为C++没有像C有realloc扩容,只有new,但是realloc也有空间不够需要异地扩容,因此使用new,直接开辟一块空间,然后把原数据拷贝过来。
5.5resize
在使用这个接口的时候,知道resize分三种情况。
1.n<_size
删除数据
2._size<n<=_capacity
插入数据
3.n>_capacity
扩容+插入数据
void String::resize(size_t n, char c)
{
//第二种情况和第三种情况放在一起
if (n > _size)
{
//在reserve判断是否扩容
reserve(n);
for (size_t i = _size; i < n; ++i)
{
_str[i] = c;
}
_size = n;
_str[_size] = '\0';
}
else
{
_str[n] = '\0';
_size = n;
}
}
6.Modify操作
//声明
void push_back(char c);
void append(const char* str);
String& operator+=(char c);
String& operator+=(const char* str);
void clear();
void swap(String& s);
const char* c_str()const;
6.1push_back
void String::push_back(char c)
{
//扩容
//构造函数的时候让_size和_capacity相等这里才可以这样判断
//不然还需要特殊处理
if (_size == _capacity)
{
//string s; 不给初始值 _capacity为0;
//s.push_back('x'); 插入数据时
//reverse(_capacity);直接这样,去开辟空间就有问题
//因此必须如下特殊处理一下
size_t newcapacity = _capacity == 0 ? 4 : 2 * _capacity;
reserve(newcapacity);
}
_str[_size++] = c;
_str[_size] = '\0';
}
6.2append
void String::append(const char* str)
{
//扩容
//插入字符串,必须要有足够空间
//因此算出插入字符串的长度
//然后才能开辟空间
int len = strlen(str);
if (_size+len > _capacity)
{
reserve(_size + len);
}
//拷贝
strcpy(_str + _size, str);
_size += len;
}
6.3operator+
//直接复用
String& String::operator+=(char c)
{
push_back(c);
return *this;
}
String& String::operator+=(const char* str)
{
append(str);
return *this;
}
6.4clear
//逻辑删除
void String::clear()
{
_size = 0;
_str[_size] = '\0';
}
6.5c_str
const char* String::c_str() const
{
return _str;
}
7.relational operators
//声明
bool operator<(const String& s);
bool operator<=(const String& s);
bool operator>(const String& s);
bool operator>=(const String& s);
bool operator==(const String& s);
bool operator!=(const String& s);
//定义
bool String::operator==(const String& s)
{
return strcmp(_str, s._str) == 0;
}
bool String::operator!=(const String& s)
{
return !operator==(s);
}
bool String::operator<(const String& s)
{
return strcmp(_str, s._str) < 0;
}
bool String::operator<=(const String& s)
{
return operator < (s) && operator == (s);
}
bool String::operator>(const String& s)
{
return strcmp(_str, s._str) > 0;
}
bool String::operator>=(const String& s)
{
return operator>(s) && operator==(s);
}
8. find函数
// 返回c在string中第一次出现的位置
size_t find(char c, size_t pos = 0) const;
// 返回子串s在string中第一次出现的位置
size_t find(const char* s, size_t pos = 0) const;
8.1返回c在string中第一次出现的位置
size_t String::find(char c, size_t pos) const
{
//自己实现遍历去找
assert(pos < _size);
for (; pos < _size; ++pos)
{
if (_str[pos] == c)
return pos;
}
return -1;
}
8.2返回子串s在string中第一次出现的位置
// 返回子串s在string中第一次出现的位置
size_t String::find(const char* s, size_t pos) const
{
assert(pos < _size);
//写法1 ,
//自己实现寻找暴力求解
//也可以使用kmp算法,这个实际效率并没有那么好
//或者其他更优字符串匹配算法之 BF、RK、BM(推荐)
//int len = stn(s);
//int begin1 = 0, begin2 = 0;
//while (pos < _size )
//{
// begin1 = pos;
// while (begin2 < len)
// {
// if (_str[begin1] != s[begin2])
// {
// begin2 = 0;
// break;
// }
// ++begin2;
// ++begin1;
// }
// if (begin2 == len)
// return pos;
// ++pos;
//}
//return -1;
//写法2 ,使用库函数
const char* ctr = strstr(_str + pos, s);
if (ctr == nullptr)
return -1;
else //返回位置,就用地址减一下就可以了。
return ctr - _str;
}
9.insert函数
//声明
String& insert(size_t pos, char c);
String& insert(size_t pos, const char* str);
9.1在pos位置上插入字符c
在pos位置插入字符,必须要把pos位置以及之后位置的字符挪动。
第一种错误写法
String& String::insert(size_t pos, char c)
{
assert(pos < _size);
if (_size == _capacity)
{
size_t newcapacity = _capacity == 0 ? 4 : 2 * _capacity;
reserve(newcapacity);
}
//写法1
int end = _size;
while (end >= pos)
{
_str[end + 1] = _str[end];
}
_str[pos] = c;
++_size;
return *this;
}
这段代码,看这似乎没有什么问题,但是真的没有问题吗?
错误:pos在0的位置
这就不得不提到C语言,算术转换的问题,比int类型大的,会把小的转化成大的类型,这个问题C++依旧存在。
当end减到-1时,因为size_t时无符号整型,-1这个数就会转换为int类型最大值4294967295。
解决方法1
pos强制类型转换成int类型
String& String::insert(size_t pos, char c)
{
assert(pos < _size);
if (_size == _capacity)
{
size_t newcapacity = _capacity == 0 ? 4 : 2 * _capacity;
reserve(newcapacity);
}
int end = _size;
while (end >= (int)pos)
{
_str[end + 1] = _str[end];
}
_str[pos] = c;
++_size;
return *this;
}
解决方法2
end定义成size_t类型,end赋值为\0下一个位置,并且当pos在零的位置,涉及算术转换的问题,因此end>pos
String& String::insert(size_t pos, char c)
{
assert(pos < _size);
//扩容
if (_size == _capacity)
{
size_t newcapacity = _capacity == 0 ? 4 : 2 * _capacity;
reserve(newcapacity);
}
size_t end = _size+1;
while (end > pos)
{
_str[end] = _str[end - 1];
--end;
}
_str[pos] = c;
++_size;
return *this;
}
9.2在pos位置上插入字符串str
这里也有pos为0的时候,涉及算术转换的问题,上面能搞懂,这段代码没问题
String& String::insert(size_t pos, const char* str)
{
size_t len = strlen(str);
if (len + _size > _capacity)
{
reserve(len + _size);
}
//挪动数据
//这里涉及算术转换,因此pos这个位置先不挪动,
//先把pos之后位置数据挪动,
size_t end1 = _size;
size_t end2 = _size + len;
while (end1 > pos)
{
_str[end2] = _str[end1];
--end1;
--end2;
}
//在挪动一下pos位置
_str[end2] = _str[pos];
//拷贝,不能使用strcpy不然会把\0也会拷贝
strncpy(_str + pos, str, len);
_size += len;
return *this;
}
10.erase函数
//删除pos开始到len位置的字符,包括pos的位置
String& erase(size_t pos, size_t len = npos);
删除的本质也是挪动数据。
如果不指定len长,默认删到字符串结束位置,或者指定len长比字符串本身长度还要长也是默认删到字符串结束位置。这两种都是逻辑删除。
String& String::erase(size_t pos, size_t len)
{
assert(pos < _size);
if (len == npos || pos + len >= _size )
{
_str[pos] = '\0';
_size = pos;
}
else
{
//不是删除到结尾,就把pos+len后面数据拷贝过来,包括\0
strcpy(_str + pos, _str + pos + len);
_size -= len;
}
return *this;
}
11.流插入<< 流提取 >>模拟实现
//不需要声明是有元函数
inline istream& operator>>(istream& in, String& s)
{
//减少频繁扩容
char buff[128] = { '\0' };
char ch = in.get();
size_t i = 0;
while (ch != ' ' && ch != '\n')
{
if (i == 127)
{
s += buff;
i = 0;
}
buff[i++] = ch;
ch = in.get();
}
if (i >= 0)
{
buff[i] = '\0';
s += buff;
}
return in;
}
static istream& getline(istream& in, String& s)
{
char buff[128] = { '\0' };
size_t i = 0;
char ch = in.get();
while (ch != '\n')
{
if (i == 127)
{
s += buff;
i = 0;
}
buff[i++] = ch;
ch = in.get();
}
if (i >= 0)
{
buff[i] = 0;
s += buff;
}
return in;
}
//写法1
//inline ostream& operator<<(ostream& out, const String& s)
//{
// out << s._str;
// return out;
//}
//写法2 不需要是有元函数
//因此并不是<<运算符重载,都必须是有元函数
inline ostream& operator<<(ostream& out, const String& s)
{
for (size_t i = 0; i < s.size(); ++i)
{
out << s[i];
}
return out;
}
string类的模拟实现到这里就结束了,如果大家发现有什么错误,麻烦在评论区留言,一起相互学习进步,期待你的点赞,评论,收藏,加关注!