[C.C++] 【C++】string的实现

578 0
Honkers 2026-3-28 03:51:10 | 显示全部楼层 |阅读模式

1.前言

前面我们说了string的使用,接下来我们就来自己实现一下string,让我们对string的理解更加深刻—>>点击查看《string的使用》

2. 框架了解

我们知道,stl容器都是使用模板来实现的,但是我们这里先不使用模板来实现,模板主要是涉及编码的问题,我们这里先不涉及那么多编码的问题,所以我们还是定义成了string.h和string.cpp以及测试test.cpp三个文件,声明和定义分离,如果是模板的话就不能声明和定义分离了

3.具体实现

1. 基本结构

字符串对我们来说就好像字符数组,所以我们底层其实是用一个字符类型的顺序表来实现的(这里为了跟标准库内的string区分开,我们使用自己的命名空间)

  1. namespace William
  2. {
  3. class string
  4. {
  5. public:
  6. private:
  7. char* _str;
  8. size_t _size;
  9. size_t _capacity;
  10. public:
  11. static size_t npos;
  12. };
复制代码
  1. 这里其实就跟我们顺序表的架构是差不多的,只不过这里的数据类型是char类型
  2. 这里的容量和大小因为都不可能为负数,所以类型使用的是size_t
  3. 这里的npos我们后续会继续说

2. 构造函数

  1. string()
  2. :_str(new char[1]{'\0'})
  3. ,_size(0)
  4. ,_capacity(0)
  5. {}
  6. string(const char* str)
  7. {
  8. _size = strlen(str);
  9. //_capacity不包含\0
  10. _capacity = _size;
  11. _str = new char[_capacity + 1];
  12. strcpy(_str, str);
  13. }
复制代码
  1. 在这里的无参构造函数中,我们注意到_str初始化时进行了new,这里是为了适配c_str,防止解引用空指针,用nullptr是会崩溃的
  2. 我们要知道这里的_capacity是不包含\0的,但是我们是需要把\0存起来的,所以我们new的时候空间是要加一的
  3. 而且这里也要注意我们初始化列表的顺序,这需要结合我们之前的类和对象知识,初始化列表中按照成员变量在类中声明顺序进行初始化,跟成员在初始化列表出现的先后顺序无关。所以这里带参的构造函数也可以不走初始化列表初始化

下面我们可以把这两个构造函数合并成一个带缺省参数的构造函数

  1. string(const char* str = "")
  2. {
  3. _size = strlen(str);
  4. _capacity = _size;
  5. _str = new char[_capacity + 1];
  6. strcpy(_str, str);
  7. }
复制代码

3. 析构函数

  1. ~string()
  2. {
  3. if (_str)
  4. {
  5. delete[] _str;
  6. _str = nullptr;
  7. _size = _capacity = 0;
  8. }
  9. }
复制代码
  1. 前面我们使用的是new[],所以我们这里的delete就要使用delete[]
  2. 析构之前要看看字符串是否为空,如果为空就不需要析构
  3. delete之后要把_str指向空指针,容量和大小要清空

4. 拷贝构造函数

  1. string(const string& s)
  2. {
  3. _str = new char[s._capacity + 1];
  4. strcpy(_str, s._str);
  5. _size = s._size;
  6. _capacity = s._capacity;
  7. }
复制代码
  1. 我们之前在类和对象里面知道,只要一个对象有显式实现的析构函数,那么就要实现深拷贝
  2. 这里的容量加一还是为了存放\0
  3. 注意我们这里的拷贝构造和后面的赋值运算符重载都是有现代写法的,我们说的都是传统写法,现代写法可以去最下面我们的源代码那里查看

5. size()以及capacity()

  1. size_t size() const
  2. {
  3. return _size;
  4. }
  5. size_t capacity() const
  6. {
  7. return _capacity;
  8. }
复制代码
  1. 这里就跟构造函数那里说的一样,容量和大小是不可能为负数的,所以我们使用了size_t类型
  2. 我们这两个接口是肯定不允许用户修改的,所以我们使用了const进行了修饰

6. c_str

  1. const char* c_str()
  2. {
  3. return _str;
  4. }
  5. const char* c_str() const
  6. {
  7. return _str;
  8. }
复制代码
  1. 这个接口可以返回C语言形式的字符串
  2. 这里实现了两个,区别就是一个是对于普通对象的一个是针对const对象的,而无论是哪种对象,我们都是不希望用户修改我们的原始字符串的,使用我们返回是也使用了const

测试

  1. void test_string1()
  2. {
  3. string s1;
  4. string s2("hello world");
  5. cout << s1.c_str() << endl;
  6. cout << s2.c_str() << endl;
  7. }
  8. int main()
  9. {
  10. William::test_string1();
  11. return 0;
  12. }
复制代码

关于这里的测试,还有一些知识需要大家回顾,就是关于声明和定义分离的相关知识,我们前面在框架那里说过,我们是创建了三个文件的,我们这里的测试是在test.cpp中实现的,但是我们要在string.h中声明,我们的string.cpp和test.cpp文件都会包含string.h这个头文件,如果我们在string.h中实现测试函数,那么在string.cpp和test.cpp中都会有一份这个测试函数,在最后链接的时候就会出现冲突

7. iterator迭代器实现

  1. typedef char* iterator;
  2. typedef const char* const_iterator;
  3. iterator begin()
  4. {
  5. return _str;
  6. }
  7. iterator end()
  8. {
  9. return _str + _size;
  10. }
  11. const_iterator begin() const
  12. {
  13. return _str;
  14. }
  15. const_iterator end() const
  16. {
  17. return _str + _size;
  18. }
复制代码
  1. 这里我们可以看到,string的迭代器底层就是字符指针
  2. 这里我们分别实现了普通对象的迭代器和const对象的迭代器
  3. 我们要知道,迭代器都是左闭右开的,所以我们这里的end其实指向的是最后一个元素的下一个位置
  4. 编译器会根据对象的类型,自动选择最合适的迭代器,这个不需要我们担心

测试

  1. void test_string1()
  2. {
  3. string s1;
  4. string s2("hello world");
  5. cout << s1.c_str() << endl;
  6. cout << s2.c_str() << endl;
  7. string::iterator it = s2.begin();
  8. while (it != s2.end())
  9. {
  10. *it += 2;
  11. cout << *it << " ";
  12. ++it;
  13. }
  14. cout << endl;
  15. for (auto ch : s2)
  16. {
  17. cout << ch << " ";
  18. }
  19. cout << endl;
  20. }
  21. int main()
  22. {
  23. William::test_string1();
  24. return 0;
  25. }
复制代码

这里我们可以看到,实现迭代器之后就可以支持范围for了

8. operator[]

这里因为[]运算符在string里面太重要了,所以我们这里单独拉出来说一下

  1. char& operator[](size_t pos)
  2. {
  3. assert(pos < _size);
  4. return _str[pos];
  5. }
  6. const char& operator[](size_t pos) const
  7. {
  8. assert(pos < _size);
  9. return _str[pos];
  10. }
复制代码
  1. 我们重载了[]之后,string就可以像数组一样实现下标访问了,这是极其方便的
  2. 这里我们也是重载了普通对象的和const对象的

测试

  1. void test_string1()
  2. {
  3. string s1;
  4. string s2("hello world");
  5. cout << s1.c_str() << endl;
  6. cout << s2.c_str() << endl;
  7. for (size_t i = 0; i < s2.size(); i++)
  8. {
  9. s2[i] += 2;
  10. }
  11. cout << s2.c_str() << endl;
  12. }
  13. int main()
  14. {
  15. William::test_string1();
  16. return 0;
  17. }
复制代码

9. reserve

  1. void string::reserve(size_t n)
  2. {
  3. if (n > _capacity)
  4. {
  5. char* tmp = new char[n + 1];
  6. strcpy(tmp, _str);
  7. delete[] _str;
  8. _str = tmp;
  9. _capacity = n;
  10. }
  11. }
复制代码
  1. 这个函数是我们扩容或者指定开辟空间大小的函数
  2. 我们默认采取只扩容不缩容的策略
  3. C++中的扩容不能像C语言中realloc那样,只能像这样先再开辟一块新空间,然后把原始字符串的内容给这个新空间拷贝过去,再让原始字符串的指针指向这个新空间
    4.注意,在这里及下面的接口中,只要是指明类域的就是我们在string.cpp文件中实现的函数,这里体现出我们一开始说的声明和定义分离

10. push_back、append和insert及operator+=

这四个接口都是实现了string中增加元素的功能

  1. void string::push_back(char ch)
  2. {
  3. if (_size == _capacity)
  4. {
  5. reserve(_capacity == 0 ? 4 :_capacity * 2);
  6. }
  7. _str[_size] = ch;
  8. ++_size;
  9. _str[_size] = '\0';
  10. }
  11. string& string::operator+=(char ch)
  12. {
  13. push_back(ch);
  14. return *this;
  15. }
  16. void string::append(const char* str)
  17. {
  18. size_t len = strlen(str);
  19. if (_size + len > _capacity)
  20. {
  21. reserve(_size + len > 2 * _capacity ? _size + len : 2 * _capacity);
  22. }
  23. strcpy(_str + _size, str);
  24. _size += len;
  25. }
  26. string& string::operator+=(const char* str)
  27. {
  28. append(str);
  29. return *this;
  30. }
  31. void string::insert(size_t pos, char ch)
  32. {
  33. assert(pos < _size);
  34. if (_size == _capacity)
  35. {
  36. reserve(_capacity == 0 ? 4 : _capacity * 2);
  37. }
  38. size_t end = _size + 1;
  39. while (end > pos)//注意这里
  40. {
  41. _str[end] = _str[end - 1];
  42. --end;
  43. }
  44. _str[pos] = ch;
  45. ++_size;
  46. }
  47. void string::insert(size_t pos, const char* str)
  48. {
  49. assert(pos < _size);
  50. size_t len = strlen(str);
  51. if (len == 0) return;
  52. if (_size + len > _capacity)
  53. {
  54. reserve(_size + len > 2 * _capacity ? _size + len : 2 * _capacity);
  55. }
  56. size_t end = _size + len;
  57. while (end > pos + len - 1)//注意这里
  58. {
  59. _str[end] = _str[end - len];
  60. --end;
  61. }
  62. for (int i = 0; i < len; i++)
  63. {
  64. _str[pos + i] = str[i];
  65. }
  66. _size += len;
  67. }
复制代码
  1. 首先我们要知道push_back接口是只能添加单个字符的,而其他接口是既可以添加字符也可以添加字符串
  2. 在push_back中一定要注意最后要加上\0
  3. 在这些接口中,我们都需要先看看容量是否足够,不够需要扩容,这里是通过reserve扩容的
  4. 这些接口中,最需要注意的就是insert接口,因为在insert接口中它是需要挪动数据的,但是这个循环的判断条件极其容易出错,最核心的原因是我们定义的类型(size_t)的问题,我们的end是size_t类型,当它减到0时本应该跳出循环,但由于它的无符号类型,当它为0再减1时本应是-1,但是-1在内存中的补码全为1,对于无符号类型来说就直接变成最大值了,就会一直循环下去导致死循环,我们这里的end很多人都会写成直接等于_size,就会出现上述的错误,这里一定要记得end是等于_size+ 1的

测试

  1. void test_string2()
  2. {
  3. string s1("hello world");
  4. s1 += '+';
  5. s1 += '*';
  6. cout << s1.c_str() << endl;
  7. s1 += "love";
  8. cout << s1.c_str() << endl;
  9. s1.insert(5, '&');
  10. cout << s1.c_str() << endl;
  11. string s2("hello world");
  12. s2.insert(5, "&&&");
  13. cout << s2.c_str() << endl;
  14. }
  15. int main()
  16. {
  17. William::test_string2();
  18. return 0;
  19. }
复制代码

我们注意到,我们的operator+=的实现是通过push_back和append的复用来实现的,所以我们这里直接测试+=和insert就行

11. erase

前面我们说了string中如何增加数据,现在我们来看看怎么减少数据

这是我们在头文件中的声明:

  1. void erase(size_t pos, size_t len = npos);
复制代码

为什么要单独把这个说一下呢,因为我们可以看看这个声明中有一个明显不同的缺省参数npos,这就是我们在基本结构那里说的那个npos,这里我们就来说一下它的左右,在基本结构那里我们可以看到它是定义成了一个全局的变量,所以我们不能在头文件中把它初始化了,只能声明它,初始化是在string.cpp中实现的,如果我们在头文件中初始化就会发生链接错误,这个npos我们认为它是size_t类型的,我们把它赋值为-1,对于无符号来说这就是整型的最大值了,即我们这里的缺省参数的意义是默认删除到字符串结束
注:这里是需要结合我们的类和对象下中的static成员部分的内容来理解的,详情请看-——>>>点击查看《类和对象下》

其实这里直接在头文件中初始化npos也是可以的,算是C++对于这个东西单独开了一个绿灯,所以大家可能会在某些地方看到直接在头文件中初始化,对于这个npos来说确实可以编译通过,但是不建议大家这样写

  1. void string::erase(size_t pos, size_t len)
  2. {
  3. assert(pos < _size);
  4. if (len >= _size - pos)
  5. {
  6. _str[pos] = '\0';
  7. _size = pos;
  8. }
  9. else
  10. {
  11. for (int i = pos + len; i <= _size; i++)
  12. {
  13. _str[i - len] = _str[i];
  14. }
  15. _size -= len;
  16. }
  17. }
复制代码
  1. erase成员函数实现的是对pos位置处开始向后len个字符的删除
  2. 我们通过上面对npos的讲解知道,如果没有传len的值,erase是默认删除到字符串结束的,而且我们要注意到没有在函数头这里再写一遍缺省参数,这是我们关于缺省参数的一个知识点>>>点击查看详情<<<
  3. 这里的删除和我们的顺序表中的删除很类似,是不需要真的去把数据清空的,只是修改string对象的大小

测试

  1. void test_string3()
  2. {
  3. string s1("hello world");
  4. s1.erase(6, 100);
  5. cout << s1.c_str() << endl;
  6. string s2("hello world");
  7. s2.erase(6);
  8. cout << s2.c_str() << endl;
  9. string s3("hello world");
  10. s3.erase(6, 3);
  11. cout << s3.c_str() << endl;
  12. }
  13. int main()
  14. {
  15. William::test_string3();
  16. return 0;
  17. }
复制代码

12. find

这是我们在头文件中的声明

  1. size_t find(char ch, size_t pos = 0);
  2. size_t find(const char* str, size_t pos = 0);
复制代码
  1. size_t string::find(char ch, size_t pos)
  2. {
  3. assert(pos < _size);
  4. for (int i = pos; i < _size; i++)
  5. {
  6. if (_str[i] == ch)
  7. {
  8. return i;
  9. }
  10. }
  11. return npos;
  12. }
  13. size_t string::find(const char* str, size_t pos)
  14. {
  15. assert(pos < _size);
  16. const char* ptr = strstr(_str + pos, str);
  17. if (ptr == nullptr)
  18. {
  19. return npos;
  20. }
  21. else
  22. {
  23. return ptr - _str;
  24. }
  25. }
复制代码
  1. find接口就是从pos位置开始查找指定字符或者字符串,如果没有指定pos,则从0位置开始查找,第一个就是查找字符,第二个是查找字符串
  2. 这里我们采用的都是暴力匹配,像KMP算法之类的本人还没有那么高的水平,字符串匹配用的是C语言中的函数,这里也体现出我们当时适配C语言的重要性

测试

我们这里把find测试和接下来的substr以及赋值运算符放在一起展示了,这样更清晰一点

13. substr

这是我们在头文件中的声明

  1. string substr(size_t pos = 0, size_t len = npos);
复制代码
  1. string string::substr(size_t pos, size_t len)
  2. {
  3. assert(pos < _size);
  4. if (len > _size - pos)
  5. {
  6. len = _size - pos;
  7. }
  8. string sub;
  9. sub.reserve(len);
  10. for (int i = 0; i < len; i++)
  11. {
  12. sub += _str[pos + i];
  13. }
  14. return sub;
  15. }
复制代码
  1. 我们这里的substr功能是从pos位置开始,获取len个字符长度的字串,这里我们从声明中可以知道pos和len都是有缺省值的,所以什么参数都不传的话,该接口会默认从字符串的起始位置开始一直到字符串结束,也就是整个字符串
  2. 注意这里是需要理解我们拷贝构造的知识的,如果这里没有拷贝构造的话,程序是会崩溃的>>>点击查看拷贝构造相关知识<<<,这里我们就简单说一下,这里我们的传值返回是需要调用拷贝构造的,sub在出了函数之后就会销毁产生一个临时变量,我们需要用这个临时变量来拷贝构造我们的子串,如果我们没有显式实现拷贝构造没有实现深拷贝的话,随着sub的销毁子串也就让子串指向一个野指针了,而且不能引用返回,也是因为sub出了作用域就会销毁

测试

这里如上面find那里说的一样

14. 赋值运算符重载

通过上面substr中的注意事项中我们看到了拷贝构造的重要性,接下来我们就会实现一个跟拷贝构造容易搞混的默认成员函数——赋值运算符重载>>>点击查看赋值运算符重载详情<<<

  1. string& operator=(const string& s)
  2. {
  3. if (this != &s)
  4. {
  5. delete[] _str;
  6. _str = new char[s._capacity + 1];
  7. strcpy(_str, s._str);
  8. _size = s._size;
  9. _capacity = s._capacity;
  10. }
  11. return *this;
  12. }
复制代码
  1. 这里的this指针就是要被赋值的对象,我们需要先把它给释放掉,再让它指向一块新空间,并把赋值的对象拷贝给要被赋值的对象
  2. 需要注意的是,在语法层面上是允许自己给自己赋值的,所以我们一定要判断一下是不是自己给自己赋值,如果是且没有做判断的话,上来就把自己释放就出错了

测试

  1. void test_string4()
  2. {
  3. string s("test.cpp.zip");
  4. size_t pos = s.find('.');
  5. string sub = s.substr(pos);
  6. cout << sub.c_str() << endl;
  7. string copy(s);
  8. cout << copy.c_str() << endl;
  9. s = sub;
  10. cout << sub.c_str() << endl;
  11. cout << s.c_str() << endl;
  12. s = s;
  13. cout << s.c_str() << endl;
  14. }
  15. int main()
  16. {
  17. William::test_string4();
  18. return 0;
  19. }
复制代码

15. 运算符重载

这是我们在头文件中的声明

  1. bool operator<(const string& s1, const string& s2);
  2. bool operator<=(const string& s1, const string& s2);
  3. bool operator>(const string& s1, const string& s2);
  4. bool operator>=(const string& s1, const string& s2);
  5. bool operator==(const string& s1, const string& s2);
  6. bool operator!=(const string& s1, const string& s2);
复制代码

这里我们并没有重载<<和>>,我们在下面会单独说这两个

  1. bool operator<(const string& s1, const string& s2)
  2. {
  3. return strcmp(s1.c_str(), s2.c_str()) < 0;
  4. }
  5. bool operator<=(const string& s1, const string& s2)
  6. {
  7. return s1 < s2 || s1 == s2;
  8. }
  9. bool operator>(const string& s1, const string& s2)
  10. {
  11. return !(s1 <= s2);
  12. }
  13. bool operator>=(const string& s1, const string& s2)
  14. {
  15. return !(s1 < s2);
  16. }
  17. bool operator==(const string& s1, const string& s2)
  18. {
  19. return strcmp(s1.c_str(), s2.c_str()) == 0;
  20. }
  21. bool operator!=(const string& s1, const string& s2)
  22. {
  23. return !(s1 == s2);
  24. }
复制代码
  1. 我们这里是直接写成全局函数了,目的是跟库中一样可以支持字符串和字符串比以及字符和字符串比等,但是我们这里只实现了字符串与字符串比较,给大家先简单说明一下
  2. 这里的比较我们只需要实现两个,剩下的就可以通过这两个复用来实现了

测试

  1. void test_string5()
  2. {
  3. string s1("hello world");
  4. string s2("hello world");
  5. cout << (s1 < s2) << endl;
  6. cout << (s1 == s2) << endl;
  7. cout << ("hello world" < s2) << endl;//隐式类型转换
  8. cout << (s1 == "hello world") << endl;//隐式类型转换
  9. //这里没有隐式类型转换,运算符重载必须用一个类类型的参数
  10. cout << ("hello world" == "hello world") << endl;
  11. }
  12. int main()
  13. {
  14. William::test_string5();
  15. return 0;
  16. }
复制代码

16. << 和 >> 重载

这是我们在头文件中的声明

  1. ostream& operator<<(ostream& out, const string& s);
  2. istream& operator>>(istream& in, string& s);//这里的istream是可以加const的
复制代码

重载完<<和>>之后我们在cout的时候就不用再调用c_str了

  1. ostream& operator<<(ostream& out, const string& s)
  2. {
  3. for (auto ch : s)
  4. {
  5. out << ch;
  6. }
  7. return out;
  8. }
  9. istream& operator>>(istream& in, string& s)//这里的istream是可以加const的
  10. {
  11. s.clear();
  12. //优化,防止频繁扩容
  13. const int N = 256;
  14. char buff[N];
  15. int i = 0;
  16. //这里由于istream直接流提取的特性,会直接忽略空格和换行,所以不能这样写
  17. /*char ch;
  18. in >> ch;
  19. while (ch != ' ' && ch != '\n')
  20. {
  21. s += ch;
  22. in >> ch;
  23. }
  24. return in;*/
  25. char ch;
  26. ch = in.get();
  27. while (ch != ' ' && ch != '\n')
  28. {
  29. buff[i++] = ch;
  30. if (i == N - 1)
  31. {
  32. buff[i] = '\0';
  33. s += buff;
  34. i = 0;
  35. }
  36. //s += ch;
  37. ch = in.get();
  38. }
  39. if (i > 0)
  40. {
  41. buff[i] = '\0';
  42. s += buff;
  43. }
  44. return in;
  45. }
复制代码
  1. << 和 >> 是必须要写成全局函数的,因为重载为成员函数this指针默认抢占了第一个形参位置,第一个形参位置是左侧运算对象,调用时就变成了对象<>>点击查看<<和>>重载详情
  2. 正如我们在代码中的注释所说的一样,我们在实现>>重载的时候一定要注意使用get函数,否则会直接忽略空格和换行

测试

  1. void test_string6()
  2. {
  3. string s("hello world");
  4. cout << s << endl;
  5. string str;
  6. cin >> str;
  7. cout << str << endl;
  8. }
  9. int main()
  10. {
  11. William::test_string6();
  12. return 0;
  13. }
复制代码

4. 源代码

1. string.h

  1. #pragma once
  2. #include<iostream>
  3. #include<assert.h>
  4. using namespace std;
  5. namespace William
  6. {
  7. class string
  8. {//短小频繁调用的函数,可以直接定义到类里面,默认是inline
  9. public:
  10. typedef char* iterator;
  11. typedef const char* const_iterator;
  12. iterator begin()
  13. {
  14. return _str;
  15. }
  16. iterator end()
  17. {
  18. return _str + _size;
  19. }
  20. const_iterator begin() const
  21. {
  22. return _str;
  23. }
  24. const_iterator end() const
  25. {
  26. return _str + _size;
  27. }
  28. //string()
  29. // :_str(new char[1]{'\0'})
  30. // ,_size(0)
  31. // ,_capacity(0)
  32. //{}
  33. //string(const char* str)
  34. //{
  35. // _size = strlen(str);
  36. // //_capacity不包含\0
  37. // _capacity = _size;
  38. // _str = new char[_capacity + 1];
  39. // strcpy(_str, str);
  40. //}
  41. //上面两个构造合并到一起
  42. string(const char* str = "")
  43. {
  44. _size = strlen(str);
  45. _capacity = _size;
  46. _str = new char[_capacity + 1];
  47. strcpy(_str, str);
  48. }
  49. //传统写法
  50. /*string(const string& s)
  51. {
  52. _str = new char[s._capacity + 1];
  53. strcpy(_str, s._str);
  54. _size = s._size;
  55. _capacity = s._capacity;
  56. }
  57. string& operator=(const string& s)
  58. {
  59. if (this != &s)
  60. {
  61. delete[] _str;
  62. _str = new char[s._capacity + 1];
  63. strcpy(_str, s._str);
  64. _size = s._size;
  65. _capacity = s._capacity;
  66. }
  67. return *this;
  68. }*/
  69. //现代写法
  70. void swap(string& s)
  71. {
  72. std::swap(_str, s._str);
  73. std::swap(_size, s._size);
  74. std::swap(_capacity, s._capacity);
  75. }
  76. string(const string& s)
  77. {
  78. string tmp(s._str);
  79. swap(tmp);//直接用std中的swap会有3次深拷贝
  80. }
  81. //string& operator=(const string& s)
  82. //{
  83. // if (this != &s)
  84. // {
  85. // //string tmp(s._str);//调用构造
  86. // string tmp(s);//调用拷贝构造
  87. // swap(tmp);
  88. // }
  89. // return *this;
  90. //}
  91. string& operator=(string tmp)
  92. {
  93. swap(tmp);
  94. return *this;
  95. }
  96. ~string()
  97. {
  98. if (_str)
  99. {
  100. delete[] _str;
  101. _str = nullptr;
  102. _size = _capacity = 0;
  103. }
  104. }
  105. const char* c_str()
  106. {
  107. return _str;
  108. }
  109. const char* c_str() const
  110. {
  111. return _str;
  112. }
  113. void clear()
  114. {
  115. _str[0] = '\0';
  116. _size = 0;
  117. }
  118. size_t size() const
  119. {
  120. return _size;
  121. }
  122. size_t capacity() const
  123. {
  124. return _capacity;
  125. }
  126. char& operator[](size_t pos)
  127. {
  128. assert(pos < _size);
  129. return _str[pos];
  130. }
  131. const char& operator[](size_t pos) const
  132. {
  133. assert(pos < _size);
  134. return _str[pos];
  135. }
  136. void reserve(size_t n);
  137. void push_back(char ch);
  138. void append(const char* str);
  139. string& operator+=(char ch);
  140. string& operator+=(const char* str);
  141. void insert(size_t pos, char ch);
  142. void insert(size_t pos, const char* str);
  143. void erase(size_t pos, size_t len = npos);
  144. size_t find(char ch, size_t pos = 0);
  145. size_t find(const char* str, size_t pos = 0);
  146. string substr(size_t pos = 0, size_t len = npos);
  147. private:
  148. char* _str = nullptr;
  149. size_t _size = 0;
  150. size_t _capacity = 0;
  151. static const size_t npos;
  152. };
  153. bool operator<(const string& s1, const string& s2);
  154. bool operator<=(const string& s1, const string& s2);
  155. bool operator>(const string& s1, const string& s2);
  156. bool operator>=(const string& s1, const string& s2);
  157. bool operator==(const string& s1, const string& s2);
  158. bool operator!=(const string& s1, const string& s2);
  159. ostream& operator<<(ostream& out, const string& s);
  160. istream& operator>>(istream& in, string& s);//这里的istream是可以加const的
  161. }
复制代码

2. string.cpp

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include"string.h"
  3. namespace William
  4. {
  5. const size_t string::npos = -1;
  6. void string::reserve(size_t n)
  7. {
  8. if (n > _capacity)
  9. {
  10. char* tmp = new char[n + 1];
  11. strcpy(tmp, _str);
  12. delete[] _str;
  13. _str = tmp;
  14. _capacity = n;
  15. }
  16. }
  17. void string::push_back(char ch)
  18. {
  19. if (_size == _capacity)
  20. {
  21. reserve(_capacity == 0 ? 4 :_capacity * 2);
  22. }
  23. _str[_size] = ch;
  24. ++_size;
  25. _str[_size] = '\0';
  26. }
  27. string& string::operator+=(char ch)
  28. {
  29. push_back(ch);
  30. return *this;
  31. }
  32. void string::append(const char* str)
  33. {
  34. size_t len = strlen(str);
  35. if (_size + len > _capacity)
  36. {
  37. reserve(_size + len > 2 * _capacity ? _size + len : 2 * _capacity);
  38. }
  39. strcpy(_str + _size, str);
  40. _size += len;
  41. }
  42. string& string::operator+=(const char* str)
  43. {
  44. append(str);
  45. return *this;
  46. }
  47. void string::insert(size_t pos, char ch)
  48. {
  49. assert(pos < _size);
  50. if (_size == _capacity)
  51. {
  52. reserve(_capacity == 0 ? 4 : _capacity * 2);
  53. }
  54. size_t end = _size + 1;
  55. while (end > pos)//注意这里
  56. {
  57. _str[end] = _str[end - 1];
  58. --end;
  59. }
  60. _str[pos] = ch;
  61. ++_size;
  62. }
  63. void string::insert(size_t pos, const char* str)
  64. {
  65. assert(pos < _size);
  66. size_t len = strlen(str);
  67. if (len == 0) return;
  68. if (_size + len > _capacity)
  69. {
  70. reserve(_size + len > 2 * _capacity ? _size + len : 2 * _capacity);
  71. }
  72. size_t end = _size + len;
  73. while (end > pos + len - 1)//注意这里
  74. {
  75. _str[end] = _str[end - len];
  76. --end;
  77. }
  78. for (int i = 0; i < len; i++)
  79. {
  80. _str[pos + i] = str[i];
  81. }
  82. _size += len;
  83. }
  84. void string::erase(size_t pos, size_t len)
  85. {
  86. assert(pos < _size);
  87. if (len >= _size - pos)
  88. {
  89. _str[pos] = '\0';
  90. _size = pos;
  91. }
  92. else
  93. {
  94. for (int i = pos + len; i <= _size; i++)
  95. {
  96. _str[i - len] = _str[i];
  97. }
  98. _size -= len;
  99. }
  100. }
  101. size_t string::find(char ch, size_t pos)
  102. {
  103. assert(pos < _size);
  104. for (int i = pos; i < _size; i++)
  105. {
  106. if (_str[i] == ch)
  107. {
  108. return i;
  109. }
  110. }
  111. return npos;
  112. }
  113. size_t string::find(const char* str, size_t pos)
  114. {
  115. assert(pos < _size);
  116. const char* ptr = strstr(_str + pos, str);
  117. if (ptr == nullptr)
  118. {
  119. return npos;
  120. }
  121. else
  122. {
  123. return ptr - _str;
  124. }
  125. }
  126. string string::substr(size_t pos, size_t len)
  127. {
  128. assert(pos < _size);
  129. if (len > _size - pos)
  130. {
  131. len = _size - pos;
  132. }
  133. string sub;
  134. sub.reserve(len);
  135. for (int i = 0; i < len; i++)
  136. {
  137. sub += _str[pos + i];
  138. }
  139. return sub;
  140. }
  141. bool operator<(const string& s1, const string& s2)
  142. {
  143. return strcmp(s1.c_str(), s2.c_str()) < 0;
  144. }
  145. bool operator<=(const string& s1, const string& s2)
  146. {
  147. return s1 < s2 || s1 == s2;
  148. }
  149. bool operator>(const string& s1, const string& s2)
  150. {
  151. return !(s1 <= s2);
  152. }
  153. bool operator>=(const string& s1, const string& s2)
  154. {
  155. return !(s1 < s2);
  156. }
  157. bool operator==(const string& s1, const string& s2)
  158. {
  159. return strcmp(s1.c_str(), s2.c_str()) == 0;
  160. }
  161. bool operator!=(const string& s1, const string& s2)
  162. {
  163. return !(s1 == s2);
  164. }
  165. ostream& operator<<(ostream& out, const string& s)
  166. {
  167. for (auto ch : s)
  168. {
  169. out << ch;
  170. }
  171. return out;
  172. }
  173. istream& operator>>(istream& in, string& s)//这里的istream是可以加const的
  174. {
  175. s.clear();
  176. //优化,防止频繁扩容
  177. const int N = 256;
  178. char buff[N];
  179. int i = 0;
  180. //这里由于istream直接流提取的特性,会直接忽略空格和换行,所以不能这样写
  181. /*char ch;
  182. in >> ch;
  183. while (ch != ' ' && ch != '\n')
  184. {
  185. s += ch;
  186. in >> ch;
  187. }
  188. return in;*/
  189. char ch;
  190. ch = in.get();
  191. while (ch != ' ' && ch != '\n')
  192. {
  193. buff[i++] = ch;
  194. if (i == N - 1)
  195. {
  196. buff[i] = '\0';
  197. s += buff;
  198. i = 0;
  199. }
  200. //s += ch;
  201. ch = in.get();
  202. }
  203. if (i > 0)
  204. {
  205. buff[i] = '\0';
  206. s += buff;
  207. }
  208. return in;
  209. }
  210. }
复制代码

3. test.cpp

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include"string.h"
  3. namespace William
  4. {
  5. void test_string1()
  6. {
  7. string s1;
  8. string s2("hello world");
  9. cout << s1.c_str() << endl;
  10. cout << s2.c_str() << endl;
  11. for (size_t i = 0; i < s2.size(); i++)
  12. {
  13. s2[i] += 2;
  14. }
  15. cout << s2.c_str() << endl;
  16. string::iterator it = s2.begin();
  17. while (it != s2.end())
  18. {
  19. *it += 2;
  20. cout << *it << " ";
  21. ++it;
  22. }
  23. cout << endl;
  24. for (auto ch : s2)
  25. {
  26. cout << ch << " ";
  27. }
  28. cout << endl;
  29. }
  30. void test_string2()
  31. {
  32. string s1("hello world");
  33. s1 += '+';
  34. s1 += '*';
  35. cout << s1.c_str() << endl;
  36. s1 += "love";
  37. cout << s1.c_str() << endl;
  38. s1.insert(5, '&');
  39. cout << s1.c_str() << endl;
  40. string s2("hello world");
  41. s2.insert(5, "&&&");
  42. cout << s2.c_str() << endl;
  43. }
  44. void test_string3()
  45. {
  46. string s1("hello world");
  47. s1.erase(6, 100);
  48. cout << s1.c_str() << endl;
  49. string s2("hello world");
  50. s2.erase(6);
  51. cout << s2.c_str() << endl;
  52. string s3("hello world");
  53. s3.erase(6, 3);
  54. cout << s3.c_str() << endl;
  55. }
  56. void test_string4()
  57. {
  58. string s("test.cpp.zip");
  59. size_t pos = s.find('.');
  60. string sub = s.substr(pos);
  61. cout << sub.c_str() << endl;
  62. string copy(s);
  63. cout << copy.c_str() << endl;
  64. s = sub;
  65. cout << sub.c_str() << endl;
  66. cout << s.c_str() << endl;
  67. s = s;
  68. cout << s.c_str() << endl;
  69. }
  70. void test_string5()
  71. {
  72. string s1("hello world");
  73. string s2("hello world");
  74. cout << (s1 < s2) << endl;
  75. cout << (s1 == s2) << endl;
  76. cout << ("hello world" < s2) << endl;//隐式类型转换
  77. cout << (s1 == "hello world") << endl;//隐式类型转换
  78. //这里没有隐式类型转换,运算符重载必须用一个类类型的参数
  79. cout << ("hello world" == "hello world") << endl;
  80. }
  81. void test_string6()
  82. {
  83. string s("hello world");
  84. cout << s << endl;
  85. string str;
  86. cin >> str;
  87. cout << str << endl;
  88. }
  89. }
  90. int main()
  91. {
  92. //William::test_string1();
  93. //William::test_string2();
  94. //William::test_string3();
  95. //William::test_string4();
  96. //William::test_string5();
  97. //William::test_string6();
  98. return 0;
  99. }
复制代码

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2026 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行