【C++】一篇文章带你深入了解string

目录

目录

  • 一. 为什么学习string?
  • 二、 标准库中的string
    • 2.1 string介绍
    • 2.2 string的常用接口说明
      • 2.2.1 string对象的常见构造
        • 2.2.1.1 [string()](https://legacy.cplusplus.com/reference/string/string/string/) —- 无参构造函数
        • 2.2.1.2 [string(const char* s)](https://legacy.cplusplus.com/reference/string/string/string/) —- 有参构造函数
        • 2.2.1.3 [string(size_t n, char c)](https://legacy.cplusplus.com/reference/string/string/string/) —- 有参构造函数
        • 2.2.1.4 [string(const string&s)](https://legacy.cplusplus.com/reference/string/string/string/) —- 拷贝构造函数
      • 2.2.2 string对象的容量操作
        • 2.2.2.1 [size 函数](https://legacy.cplusplus.com/reference/string/string/size/)
        • 2.2.2.2 [length 函数](https://legacy.cplusplus.com/reference/string/string/length/)
        • 2.2.2.3 [capacity 函数](https://legacy.cplusplus.com/reference/string/string/capacity/)
        • 2.2.2.4[ empty 函数](https://legacy.cplusplus.com/reference/string/string/empty/)
        • 2.2.2.5 [clear 函数](https://legacy.cplusplus.com/reference/string/string/clear/)
        • 2.2.2.6 [reserve 函数](https://legacy.cplusplus.com/reference/string/string/reserve/)
        • 2.2.2.7 [resize 函数](https://legacy.cplusplus.com/reference/string/string/resize/)
      • 2.2.3 string对象的访问及遍历操作
        • 2.2.3.1 [operator[]](https://legacy.cplusplus.com/reference/string/string/operator%5B%5D/)
        • 2.2.3.2 迭代器 [begin ](https://legacy.cplusplus.com/reference/string/string/begin/)、[end](https://legacy.cplusplus.com/reference/string/string/end/)
        • 2.2.3.3 迭代器 [rbegin](https://legacy.cplusplus.com/reference/string/string/rbegin/) 、[rend](https://legacy.cplusplus.com/reference/string/string/rend/)
        • 2.2.3.4 范围for
      • 2.2.4. string对象的增删查改
        • 2.2.4.1 [push_back 函数](https://legacy.cplusplus.com/reference/string/string/push_back/)
        • 2.2.4.2 [operator+=](https://legacy.cplusplus.com/reference/string/string/operator+=/)
        • 2.2.4.3 [append 函数](https://legacy.cplusplus.com/reference/string/string/append/)
        • 2.2.4.4 [insert 函数](https://legacy.cplusplus.com/reference/string/string/insert/)
        • 2.2.4.5 [erase 函数](https://legacy.cplusplus.com/reference/string/string/erase/)
        • 2.2.4.6 [npos](https://legacy.cplusplus.com/reference/string/string/npos/)
        • 2.2.4.7 [c_str 函数](https://legacy.cplusplus.com/reference/string/string/c_str/)
        • 2.2.4.8 [find 函数](https://legacy.cplusplus.com/reference/string/string/find/)
        • 2.2.4.9 [rfind 函数](https://legacy.cplusplus.com/reference/string/string/rfind/)
        • 2.2.4.10 [substr 函数](https://legacy.cplusplus.com/reference/string/string/substr/)
  • 三、string拷贝问题
    • 3.1 经典的string问题
    • 3.2 浅拷贝
    • 3.3 深拷贝
    • 3.4 写时拷贝
  • 四、string的模拟实现
    • 4.1 string默认成员函数的实现
    • 4.2 string 中 c_str 、size 、capacity 和 empty 的实现
    • 4.3 string 中 resize 和 reverse 的实现
    • 4.4 string 中 push_back 、append 和 operator+= 的实现
    • 4.5 string 中 operator[] 的实现
    • 4.6 string 中 迭代器 的实现
    • 4.7 string 中 operator<< 和 operator>> 的实现
    • 4.8 string 中 比较函数 的实现
    • 4.9 string 中 find 的实现
    • 4.10 string 中 insert 和 erase 的实现
    • 4.11 string 中 substr 的实现
    • 4.12 string 实现汇总及函数测试
  • 结尾

一. 为什么学习string?

C语言中,字符串是以’\0’结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。

二、 标准库中的string

2.1 string介绍

string的文档介绍

  1. 字符串是表示字符序列的类。
  2. 标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作单字节字符字符串的设计特性。
  3. string是使用char(即作为它的字符类型,使用它的默认char_traits分配器类型(关于模板的更多信息,请参阅basic_string)。
  4. string类是basic_string模板类的一个实例,它使用char来实例化basic_string模板类,并用char_traitsallocator作为basic_string的默认参数(根于更多的模板信息请参考basic_string)。
  5. 注意,这个类独立于所使用的编码来处理字节:如果用来处理多字节或变长字符(如UTF-8)的序列,这个类的所有成员(如长度或大小)以及它的迭代器,将仍然按照字节(而不是实际编码的字符)来操作。

总结:

  1. string是表示字符串的字符串类
  2. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
  3. string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator>string;
  4. 不能操作多字节或者变长字符的序列。

在使用string时,必须包含#include头文件以及using namespace std;

2.2 string的常用接口说明

2.2.1 string对象的常见构造

2.2.1.1 string() —- 无参构造函数
构造空的string对象,即空字符串
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s;
	cout << s <<endl;

	return 0;
}

2.2.1.2 string(const char* s) —- 有参构造函数
用C-string来构造string对象
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("chineseprson");
	cout << s << endl;

	return 0;
}

2.2.1.3 string(size_t n, char c) —- 有参构造函数
string对象中包含n个字符c
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s(10,'z');
	cout << s << endl;

	return 0;
}

2.2.1.4 string(const string&s) —- 拷贝构造函数
拷贝构造函数
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("chineseprson");
	string ss(s);
	cout << s << endl;
	cout << ss << endl;

	return 0;
}

2.2.2 string对象的容量操作

2.2.2.1 size 函数
返回字符串有效字符长度
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("chineseprson");

	cout << s.size() << endl;

	return 0;
}

2.2.2.2 length 函数
返回字符串有效字符长度
size() 与 length() 方法底层实现原理完全相同,
引入 size() 的原因是为了与其他容器的接口保持一致,
一般情况下基本都是用 size()。
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("chineseprson");

	cout << s.length() << endl;

	return 0;
}

2.2.2.3 capacity 函数
返回空间总大小
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("chineseprson");

	cout << s.capacity() << endl;

	return 0;
}

2.2.2.4 empty 函数
检测字符串释放为空串,是返回true,否则返回false

#include <iostream>
#include <string>

using namespace std;
int main()
{
	string s;
	string ss("chineseprson");

	cout << s.empty() << endl;
	cout << ss.empty() << endl;

	return 0;
}
2.2.2.5 clear 函数
清空有效字符
clear()只是将string中有效字符清空,不改变底层空间大小。
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("chineseprson");
	cout << s << endl;

	s.clear();
	cout << s << endl;

	return 0;
}

2.2.2.6 reserve 函数
为字符串预留空间
reserve(size_t res_arg=0):
为string预留空间,不改变有效元素个数,
当reserve的参数小于string的底层空间总大小时,
reserver不会改变容量小。
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("chineseprson");

	s.reserve(30);
	cout << s << endl;

	return 0;
}

2.2.2.7 resize 函数
resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,
不同的是当字符个数增多时:resize(n)用 '\0' 来填充多出的元素空间,
resize(size_t n, char c)用字符c来填充多出的元素空间。
注意:resize在改变元素个数时,如果是将元素个数增多,
可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("chineseprson");
	cout << s << endl;

	s.resize(30,'6');
	cout << s << endl;

	return 0;
}

2.2.3 string对象的访问及遍历操作

2.2.3.1 operator[]
返回pos位置的字符,const string对象调用
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("chineseprson");
	for (int i = 0; i < s.size(); i++)
	{
		printf("[%d] : %c\n", i, s[i]);
	}
	cout << endl;

	return 0;
}

2.2.3.2 迭代器 begin 、end
begin 获取第一个字符的迭代器 
end 获取最后一个字符下一个位置的迭代器
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("chineseprson");
	
	string::iterator it = s.begin();
	while (it != s.end())
	{
		cout << *it << ' ';
		it++;
	}

	cout << endl;

	return 0;
}

2.2.3.3 迭代器 rbegin 、rend
rbegin 获取最后一个字符的迭代器 
rend 获取第一个字符前一个位置的迭代器
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("chineseprson");

	string::reverse_iterator it = s.rbegin();
	while (it != s.rend())
	{
		cout << *it << ' ';
		it++;
	}

	cout << endl;

	return 0;
}

2.2.3.4 范围for

范围for作为C++新出的遍历方法,相对于以前的遍历方式它能够更加简洁的遍历数组、容器等数据结构中的元素。

#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("chineseprson");

	for (auto ch : s)
	{
		cout << ch << ' ';
	}

	cout << endl;

	return 0;
}

2.2.4. string对象的增删查改

2.2.4.1 push_back 函数
在字符串后面加一个字符
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("chineseprson");

	s.push_back('6');
	cout << s << endl;

	s.push_back('6');
	cout << s << endl;

	s.push_back('6');
	cout << s << endl;

	return 0;
}

2.2.4.2 operator+=
string& operator+= (const string& str);
operator+= 能够在字符串最后追加一个string对象内的字符串

string& operator+= (const char* s);
string& operator+= (char c);
operator+= 能够在字符串后面加一个字符或者字符串
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("chineseprson");

	s += '6';
	cout << s << endl;

	s += "666666";
	cout << s << endl;

	string ss("牛牛牛");

	s += ss;
	cout << s << endl;
	return 0;
}

2.2.4.3 append 函数
string& append (const string& str);
append 函数能够在字符串最后追加一个string对象内的字符串

string& append (const string& str, size_t subpos, size_t sublen);
append 函数能够在字符串最后追加一个string对象内的字符串的一段字符串

string& append (const char* s);
append 函数能够在字符串最后追加一个string对象内的字符串

string& append (const char* s, size_t n);
append 函数还能够在字符串后面追加字符串的前 n 个

string& append (size_t n, char c);
append 函数能够在字符串后面追加 n 个字符

注意append 函数与 operator+= 作用有部分相同
若是单纯在字符串后面追加一个字符或者字符串,更习惯使用 operator+=

#include <iostream>
#include <string>

using namespace std;
int main()
{
	string s("chineseprson");

	// 追加n个字符
	s.append(1,'6');
	cout << s << endl;

	// 追加一个字符串
	s.append("666666");
	cout << s << endl;

	// 追加一个字符串的前n个
	s.append("888888888", 3);

	cout << s << endl;
	return 0;
}

2.2.4.4 insert 函数
string& insert (size_t pos, const string& str);
insert函数能够在字符串任意位置插入一个string容器内的字符串

string& insert (size_t pos, const string& str, size_t subpos, size_t sublen);
insert函数能够在字符串任意位置插入一个string对象内的字符串的一段字符串

string& insert (size_t pos, const char* s);
insert函数能够在字符串一段字符串

string& insert (size_t pos, const char* s, size_t n);
insert 函数还能够在字符串任意位置插入字符串的前 n 个

string& insert (size_t pos, size_t n, char c);
insert 函数还能够在字符串任意位置插入n个字符
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("student");
	string ss("test");


	// 在第三个位置插入string
	s.insert(1, ss);
	cout << s << endl;

	// 在最后插入string的一部分
	s.insert(s.size(), ss , 0 , 2);
	cout << s << endl;

	// 在第一个位置插入string
	s.insert(0,"666");
	cout << s << endl;

	// 其他插入方法一样,这里省略
	return 0;
}

2.2.4.5 erase 函数
string& erase (size_t pos = 0, size_t len = npos);
erase 函数能够删除第 n 个位置后面长度为 len 的字符串

如果没有传 len 或是 第 n 个位置后面的字符数小于 len ,则n后面的字符全部删除
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("student");
	
	s.erase(4, 2);
	cout << s << endl;

	s.erase(1);
	cout << s << endl;

	return 0;
}

2.2.4.6 npos
npos的值通常是一个很大的正数,等于-1(当作为无符号数解释时)
或等于string::size_type的最大可能值。

2.2.4.7 c_str 函数
返回C格式字符串

在C++中,printf 是一个C语言函数,它不支持直接打印std::string类型的内容。这是因为 printf 是一个可变参数函数,而 std::string 不是基本数据类型,因此需要转换为C风格字符串才能由 printf 输出。

#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("chineseprson");

	printf("%s\n", s);
	printf("%s\n", s.c_str());

	return 0;
}

2.2.4.8 find 函数
size_t find (const string& str, size_t pos = 0) const;
find 函数能够从第 pos 个位置开始从前往后查找包含 string 对象 str 的字符串的位置

size_t find (const char* s, size_t pos = 0) const;
find 函数能够从第 pos 个位置开始从前往后查找包含字符串 s 的位置

size_t find (char c, size_t pos = 0) const;
find 函数能够从第 pos 个位置开始从前往后查找包含字符 c 的位置

find 函数若是能找到则返回包含需要查找内容第一个字符位置,否则返回 npos。
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("student test");
	string str("student");

	// 查找 str --> 找得到
	int pos = s.find(str, 0);
	cout << "str pos : " << pos << endl;

	// 查找字符串 --> 找得到
	pos = s.find("test" , 0);
	cout << "test pos : " << pos << endl;

	// 查找字符串 --> 找不到
	pos = s.find("Test", 0);
	cout << "Test pos : " << pos << endl;

	// 查找字符 --> 找得到
	pos = s.find('s', 0);
	cout << "s pos : " << pos << endl;

	// 查找字符 --> 找不到
	pos = s.find('a', 0);
	cout << "a pos : " << pos << endl;

	return 0;
}

2.2.4.9 rfind 函数
size_t rfind (const string& str, size_t pos = npos) const;
find 函数能够从第 pos 个位置开始从后往前查找包含 string 对象 str 的字符串的位置

size_t rfind (const char* s, size_t pos = npos) const;
find 函数能够从第 pos 个位置开始从前往后查找包含字符串 s 的位置

size_t rfind (char c, size_t pos = npos) const;
find 函数能够从第 pos 个位置开始从前往后查找包含字符 c 的位置
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("student test");
	string str("student");

	// 查找 str --> 找得到
	int pos = s.rfind(str, s.size()-1);
	cout << "str pos : " << pos << endl;

	// 查找字符串 --> 找得到
	pos = s.rfind("test", s.size() - 1);
	cout << "test pos : " << pos << endl;

	// 查找字符串 --> 找不到
	pos = s.rfind("test", s.size() - 5);
	cout << "test pos : " << pos << endl;

	// 查找字符串 --> 找不到
	pos = s.rfind("Test", s.size() - 1);
	cout << "Test pos : " << pos << endl;

	// 查找字符 --> 找得到
	pos = s.rfind('s', s.size() - 1);
	cout << "s pos : " << pos << endl;

	// 查找字符 --> 找不到
	pos = s.rfind('a', s.size() - 1);
	cout << "a pos : " << pos << endl;

	return 0;
}

2.2.4.10 substr 函数
string substr (size_t pos = 0, size_t len = npos) const;
在字符串中从第pos个位置开始截取len个字符返回
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s("student test");
	// 在s中从第0个位置开始截取所有字符返回
	string ss = s.substr(0);
	cout << ss << endl;

	// 在s中从第3个位置开始截取3字符返回
	ss = s.substr(3,3);
	cout << ss << endl;

	return 0;
}

三、string拷贝问题

3.1 经典的string问题

上面已经对string进行了简单的介绍,大家只要能够正常使用即可。在面试中,面试官总喜欢让学生自己来模拟实现string,最主要是实现string的构造、拷贝构造、赋值运算符重载以及析构函数。大家看下以下string的实现是否有问题?

// 为了和标准库区分,此处使用String
class String
{
public:
    /*String()
:_str(new char[1])
{*_str = '\0';}
*/
//String(const char* str = "\0") 错误示范
//String(const char* str = nullptr) 错误示范
    String(const char* str = "")
    {
        // 构造String对象时,如果传递nullptr指针,可以认为程序非
        if (nullptr == str)
        {
            assert(false);
            return;
        }
        _str = new char[strlen(str) + 1];
        strcpy(_str, str);
    }
    ~String()
    {
        if (_str)
        {
            delete[] _str;
            _str = nullptr;
        }
    }
private:
    char* _str;
};
// 测试
void TestString()
{
    String s1("hello C++!!!");
    String s2(s1);
}


说明:上述String没有显式定义其拷贝构造函数与赋值运算符重载,此时编译器会合成默认的,当用s1构造s2时,编译器会调用默认的拷贝构造。最终导致的问题是,s1、s2共用同一块内存空间,在释放时同一块空间被释放多次而引起程序崩溃,这种拷贝方式,称为浅拷贝

3.2 浅拷贝

浅拷贝:也称位拷贝,编译器只是将对象中的值拷贝过来。如果对象中管理资源,最后就会导致多个对象共享同一份资源,当一个对象销毁时就会将该资源释放掉,而此时另一些对象不知道该资源已经被释放,以为还有效,所以当继续对资源进项操作时,就会发生发生了访问违规。

可以采用深拷贝解决浅拷贝问题,即:每个对象都有一份独立的资源,不要和其他对象共享。

3.3 深拷贝

如果一个类中涉及到资源的管理,其拷贝构造函数、赋值运算符重载以及析构函数必须要显式给出。一般情
况都是按照深拷贝方式提供。

3.4 写时拷贝

写时拷贝就是一种拖延症,是在浅拷贝的基础之上增加了引用计数的方式来实现的。

引用计数:用来记录资源使用者的个数。在构造时,将资源的计数给成1,每增加一个对象使用该资源,就给计数增加1,当某个对象被销毁时,先给该计数减1,然后再检查是否需要释放资源,如果计数为1,说明该对象时资源的最后一个使用者,将该资源释放;否则就不能释放,因为还有其他对象在使用该资源。

四、string的模拟实现

4.1 string默认成员函数的实现

#include <iostream>
#include <assert.h>
using namespace std;

namespace aj
{
    class string
    {
    public:
        // 这里缺省值给""的原因是空字符串本身就带一个'\0'
        // 而不是初始化的时候_str为nullptr
        // 初始化列表的顺序应该与声明相同
        string(const char* str = "")
            :_capacity(strlen(str))
            , _size(_capacity)
        {
            // 多开一个空间用来存放'\0'
            _str = new char[_capacity + 1];
            strcpy(_str, str);
        }
		
		// 拷贝构造函数传统写法:
        /*string(const string& s)
        {
            _capacity = s._capacity;
            _str = new char[_capacity + 1];
            _size = s._size;
            strcpy(_str, s._str);
        }*/

		// swap函数
		void swap(string& s)
        {
            std::swap(_str, s._str);
            std::swap(_capacity, s._capacity);
            std::swap(_size, s._size);
        }

        // 拷贝构造函数现代写法:
        // 构造一个使用s构造string对象tmp
        // tmp中的内容是this指向的对象所需要的
        // 将两个对象的指针交换
        // 即可达到我们的目的
        string(const string& s)
            : _str(nullptr)
            , _capacity(0)
            , _size(0)
        {
            string tmp(s._str);
            swap(tmp);
        }
		
		// 赋值重载的传统写法:
		// 这里的传统写法与上面的拷贝构造的内容几乎相同
		// 而下面的现代写法复用了拷贝构造
		// 使得成员函数看起来更加简洁
		
        // 赋值重载 传统写法
        /*string& operator=(const string& s)
        {
            if (this != &s)
            {
                reserve(s._capacity);
                strcpy(_str, s._str);
                _capacity = s._capacity;
                _size = s._size;
            }

            return *this;
        }*/
		
		// 赋值重载的现代写法:
		// 首先判断是否是自己给自己赋值
		// 若是直接返回自己,否则进行下面的操作
		// 利用拷贝构造得来tmp
		// tmp中的数据是我们需要的数据
		// 而this指向的数据是我们需要改变的
		// tmp是临时变量,出了作用域会自动销毁
		// 我们将tmp的内容和this指向的内容交换
		// 实质上是两个指针的指向变化
		// 交换后this指向的内容就是我们需要的,返回
		// 而tmp中的内容是不需要的,出了作用域自动销毁

        // 赋值重载 现代写法
        /*string& operator=(const string& s)
        {
            if (this != &s)
            {
                string tmp(s);
                swap(tmp);
            }

            return *this;
        }*/
		
		// 拷贝构造函数的现代写法:
		// 这个现代写法与上面的本质相同
		// 这个是不判断是否是自己给自己赋值
		// 而是传值传参时利用拷贝构造直接得来tmp
		// 其他步骤相同
		
		// 赋值重载 现代写法
        string& operator=(string tmp)
        {
            swap(tmp);

            return *this;
        }
		
		// 析构函数
        ~string()
        {
            delete[] _str;
            _str = nullptr;
            _size = _capacity = 0;
        }

    private:
        char* _str;
        size_t _capacity;
        size_t _size;

        const static size_t npos;
    };

    const size_t string::npos = -1;
};

4.2 string 中 c_str 、size 、capacity 和 empty 的实现

#include <iostream>
#include <assert.h>
using namespace std;

#include <string>

namespace aj
{
    class string
    {
    public:
        void clear()
        {
            _str[0] = '\0';
            _size = 0;
        }

        const char* c_str()const
        {
            return _str;
        }

        size_t size()const
        {
            return _size;
        }

        size_t capacity() const
        {
            return _capacity;
        }

        bool empty()const
        {
            return _size == 0;
        }

    private:
        char* _str;
        size_t _capacity;
        size_t _size;

        const static size_t npos;
    };
    const size_t string::npos = -1;
};

4.3 string 中 resize 和 reverse 的实现

#include <iostream>
#include <assert.h>
using namespace std;

namespace aj
{
    class string
    {
    public:
        // 分三种情况 (n为新字符串的长度)
        //  (1) n <= _size
        //  (2) n > _size && n <= _capacity
        //  (3) n > _capacity
        // 第一种情况为缩短,第二三种情况为增长,
        // 但第二种情况不需要扩容,第三种情况不需要
        // 由于resize内部当传入的参数小于_capacity 时不会扩容
        // 所以将第二三种情况放在一起

        void resize(size_t n, char c = '\0')
        {
            if (n <= _size)
            {
                _str[n] = '\0';
                _size = n;
            }
            else
            {
                reserve(n);
                _capacity = n;
                while (_size < n)
                {
                    _str[_size] = c;
                    _size++;
                }
                // 到这里 _size = n
                _str[_size] = '\0';
            }
        }

        void reserve(size_t n)
        {
            if (n > _capacity)
            {
                // _capacity 记录的是需要存储有效数据的个数
                // 所以我们这里要多开一个空间用来记录'\0'
                char* tmp = new char[n + 1];
                strcpy(tmp, _str);
                delete[] _str;
                _str = tmp;

                _capacity = n;
            }

        }

    private:
        char* _str;
        size_t _capacity;
        size_t _size;

        const static size_t npos;
    };

    const size_t string::npos = -1;
};

4.4 string 中 push_back 、append 和 operator+= 的实现

#include <iostream>
#include <assert.h>
using namespace std;

namespace aj
{
    class string
    {
    public:
        void push_back(char c)
        {
            if (_size + 1 > _capacity)
            {
                // 这里不能盲目的开二倍,因为string可能是空字符串,
                // _capacity = 0 , 那么这里的二倍就没有意义,继续下面的操作会报错
                reserve(_capacity == 0 ? 4 : 2 * _capacity);
            }

            _str[_size] = c;
            _size++;
            _str[_size] = '\0';
        }

        void append(const char* str)
        {
            int len = strlen(str);
            if (_size + len > _capacity)
            {
                reserve(_size + len);
            }

            strcpy(_str + _size, str);
            _size += len;
        }
        
		string& operator+=(char c)
        {
            push_back(c);
            return *this;
        }

        void reserve(size_t n)
        {
            if (n > _capacity)
            {
                // _capacity 记录的是需要存储有效数据的个数
                // 所以我们这里要多开一个空间用来记录'\0'
                char* tmp = new char[n + 1];
                strcpy(tmp, _str);
                delete[] _str;
                _str = tmp;

                _capacity = n;
            }

        }
    private:
        char* _str;
        size_t _capacity;
        size_t _size;

        const static size_t npos;
    };

    const size_t string::npos = -1;
};

4.5 string 中 operator[] 的实现

#include <iostream>
#include <assert.h>
using namespace std;

namespace aj
{
    class string
    {
    public:
        char& operator[](size_t index)
        {
            return _str[index];
        }

        const char& operator[](size_t index)const
        {
            return _str[index];
        }

    private:
        char* _str;
        size_t _capacity;
        size_t _size;

        const static size_t npos;
    };

    const size_t string::npos = -1;
};

4.6 string 中 迭代器 的实现

#include <iostream>
#include <assert.h>
using namespace std;

namespace aj
{
    class string
    {

    public:
        typedef char* iterator;
        typedef const char* const_iterator;

    public:
        iterator begin()
        {
            return _str;
        }

        iterator end()
        {
            return _str + _size;
        }

        const_iterator begin() const
        {
            return _str;
        }

        const_iterator end() const
        {
            return _str + _size;
        }

    private:
        char* _str;
        size_t _capacity;
        size_t _size;

        const static size_t npos;
    };

    const size_t string::npos = -1;
};

4.7 string 中 operator<< 和 operator>> 的实现

并不是所有的流插入、流提取都需要定义成友元函数,定义成友元函数的目的是为了访问成员的私有,这里不需要访问私有,则不需要定义成友元函数。

#include <iostream>
#include <assert.h>
using namespace std;

namespace aj
{
    class string
    {
    private:
        char* _str;
        size_t _capacity;
        size_t _size;

        const static size_t npos;
    };

    const size_t string::npos = -1;

    ostream& operator<<(ostream& _cout, const string& s)
    {
        for (auto ch : s)
        {
            cout << ch;
        }

        return _cout;
    }
	
	// 这个版本不好在,没有提前开空间
	// 即使开空间了,也不知道开多少
	// 大了浪费,小了又需要很多次扩容
    //istream& operator>>(istream& _cin, string& s)
    //{
    //    // 流插入时需要将string中字符串清除
    //    s.clear();
    //    char ch = 0;
    //    ch = _cin.get();
    //    while (ch != ' ' && ch != '\n')
    //    {
    //        s += ch;
    //        ch = _cin.get();
    //    }
    //    return _cin;
    //}

    istream& operator>>(istream& _cin, string& s)
    {
        // 流插入时需要将string中字符串清除
        s.clear();
        // 定义一个buff数组,作为缓冲
        char buff[129] = { 0 };
        char ch = 0;
        ch = _cin.get();
        int i = 0;
        while (ch != ' ' && ch != '\n')
        {
            buff[i] = ch;
            ch = _cin.get();
            if (i == 128)
            {
                s += buff;
                i = 0;
            }
            i++;
        }

        if (i != 0)
        {
            s += buff;
        }
        return _cin;
    }
};

4.8 string 中 比较函数 的实现

#include <iostream>
#include <assert.h>
using namespace std;

namespace aj
{
    class string
    {
    public:
        bool operator<(const string& s)
        {
            return strcmp(_str, s._str) < 0;
        }

        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)
        {
            return strcmp(_str, s._str) == 0;
        }

        bool operator!=(const string& s)
        {
            return !(*this == s);
        }

    private:
        char* _str;
        size_t _capacity;
        size_t _size;

        const static size_t npos;
    };

    const size_t string::npos = -1;
};

4.9 string 中 find 的实现

#include <iostream>
#include <assert.h>
using namespace std;

namespace aj
{
    class string
    {
    public:
        // 返回c在string中第一次出现的位置

        size_t find(char c, size_t pos = 0) const
        {
            assert(pos < _size);
            for (size_t i = pos; i < _size; i++)
            {
                if (_str[i] == c)
                {
                    return i;
                }
            }

            return npos;
        }

        // 返回子串s在string中第一次出现的位置

        size_t find(const char* s, size_t pos = 0) const
        {
            assert(pos < _size);
            char* ret = strstr(_str, s);
            if (ret == nullptr)
            {
                return npos;
            }
            return ret - _str;
        }

    private:
        char* _str;
        size_t _capacity;
        size_t _size;

        const static size_t npos;
    };

    const size_t string::npos = -1;
};

4.10 string 中 insert 和 erase 的实现

#include <iostream>
#include <assert.h>
using namespace std;

namespace aj
{
    class string
    {
    public:
        string& insert(size_t pos, char c)
        {
            assert(pos <= _size);

            if (_size + 1 > _capacity)
            {
                reserve(_capacity == 0 ? 4 : 2 * _capacity);
            }

            // 注意:无符号整形比较是用补码进行比较
            // 当pos = 0,且 i = -1 时 , 0并不比-1大
            // 记得将_size位置上的'\0'也向后移动

            // 版本一 存在问题
            /*for (size_t i = _size; pos <= i; i--)
            {
                _str[i + 1] = _str[i];
            }*/

            // 版本二 将pos转换为有符号整形进行比较
            /*for (int i = _size; (int)pos <= i; i--)
            {
                _str[i + 1] = _str[i];
            }*/

            // 版本三 将 i 置为_size 的后面从后往前移动,防止了0与-1的比较
            for (size_t i = _size + 1; pos < i; i--)
            {
                _str[i] = _str[i - 1];
            }

            _str[pos] = c;
            _size++;

            return *this;
        }

        string& insert(size_t pos, const char* str)
        {
            assert(pos <= _size);

            int len = strlen(str);

            if (_size + len > _capacity)
            {
                reserve(_size + len);
            }

            for (size_t i = _size + len; pos < i; i--)
            {
                _str[i] = _str[i - len];
            }

            strncpy(_str + pos, str, len);

            _size += len;

            return *this;
        }


        string& erase(size_t pos, size_t len = npos)
        {
            assert(pos < _size);

            if (len + pos > _capacity || len == npos)
            {
                _str[pos] = '\0';
                _size = pos;
            }
            else
            {
                size_t begin = len + pos;
                while (begin <= _size)
                {
                    _str[pos] = _str[begin];
                    pos++;
                    begin++;
                }
                _size -= len;
            }
            return *this;
        }

    private:
        char* _str;
        size_t _capacity;
        size_t _size;

        const static size_t npos;
    };

    const size_t string::npos = -1;
};

4.11 string 中 substr 的实现

#include <iostream>
#include <assert.h>
using namespace std;

namespace aj
{
    class string
    {
    public:
        string substr(size_t pos = 0, size_t len = npos) const
        {
            assert(pos < _size);
            string tmp;
            int end = pos + len;
            if (pos + len > _size || len == npos)
            {
                len = _size - pos;
                end = _size;
            }
            
            // 提前开空间防止扩容
            tmp.reserve(len);

            for (int i = pos; i < end; i++)
            {
                tmp += _str[i];
            }

            return tmp;
        }

    private:
        char* _str;
        size_t _capacity;
        size_t _size;

        const static size_t npos;
    };

    const size_t string::npos = -1;
};

4.12 string 实现汇总及函数测试

#pragma once

#include <iostream>
#include <assert.h>
using namespace std;

#include <string>

namespace aj
{
    class string
    {
        // friend ostream& operator<<(ostream& _cout, const aj::string& s);
        // friend istream& operator>>(istream& _cin, aj::string& s);

    public:
        typedef char* iterator;
        typedef const char* const_iterator;

    public:
        // 这里缺省值给""的原因是空字符串本身就带一个'\0'
        // 而不是初始化的时候_str为nullptr
        // 初始化列表的顺序应该与声明相同
        string(const char* str = "")
            :_capacity(strlen(str))
            , _size(_capacity)
        {
            // 多开一个空间用来存放'\0'
            _str = new char[_capacity + 1];
            strcpy(_str, str);
        }
		
		// 拷贝构造函数传统写法:
        /*string(const string& s)
        {
            _capacity = s._capacity;
            _str = new char[_capacity + 1];
            _size = s._size;
            strcpy(_str, s._str);
        }*/

		// swap函数
		void swap(string& s)
        {
            std::swap(_str, s._str);
            std::swap(_capacity, s._capacity);
            std::swap(_size, s._size);
        }

        // 拷贝构造函数现代写法:
        string(const string& s)
            : _str(nullptr)
            , _capacity(0)
            , _size(0)
        {
            string tmp(s._str);
            swap(tmp);
        }
		
        // 赋值重载 传统写法
        /*string& operator=(const string& s)
        {
            if (this != &s)
            {
                reserve(s._capacity);
                strcpy(_str, s._str);
                _capacity = s._capacity;
                _size = s._size;
            }

            return *this;
        }*/
		
        // 赋值重载 现代写法
        /*string& operator=(const string& s)
        {
            if (this != &s)
            {
                string tmp(s);
                swap(tmp);
            }

            return *this;
        }*/
		
		// 赋值重载 现代写法
        string& operator=(string tmp)
        {
            swap(tmp);

            return *this;
        }
		
		// 析构函数
        ~string()
        {
            delete[] _str;
            _str = nullptr;
            _size = _capacity = 0;
        }

        //

        // iterator

        iterator begin()
        {
            return _str;
        }

        iterator end()
        {
            return _str + _size;
        }

        const_iterator begin() const
        {
            return _str;
        }

        const_iterator end() const
        {
            return _str + _size;
        }



        /

        // modify

        void push_back(char c)
        {
            if (_size + 1 > _capacity)
            {
                // 这里不能盲目的开二倍,因为string可能是空字符串,
                // _capacity = 0 , 那么这里的二倍就没有意义,继续下面的操作会报错
                reserve(_capacity == 0 ? 4 : 2 * _capacity);
            }

            _str[_size] = c;
            _size++;
            _str[_size] = '\0';
        }

        string& operator+=(char c)
        {
            push_back(c);
            return *this;
        }


        // 分为两种情况
        // (1) 追加后的字符串没有超过_capacity
        // (2) 追加后的字符串超过_capacity需要扩容

        void append(const char* str)
        {
            int len = strlen(str);
            if (_size + len > _capacity)
            {
                reserve(_size + len);
            }

            strcpy(_str + _size, str);
            _size += len;
        }

        string& operator+=(const char* str)
        {
            append(str);
            return *this;
        }

        void clear()
        {
            _str[0] = '\0';
            _size = 0;
        }

        void swap(string& s)
        {
            std::swap(_str, s._str);
            std::swap(_capacity, s._capacity);
            std::swap(_size, s._size);

        }

        const char* c_str()const
        {
            return _str;
        }



        /

        // capacity

        size_t size()const
        {
            return _size;
        }

        size_t capacity() const
        {
            return _capacity;
        }

        bool empty()const
        {
            return _size == 0;
        }

        // 分三种情况 (n为新字符串的长度)
        // (1)n <= _size
        //  (2) n > _size && n <= _capacity
        //  (3) n > _capacity
        // 第一种情况为缩短,第二三种情况为增长,
        // 但第二种情况不需要扩容,第三种情况不需要
        // 由于reserve内部当传入的参数小于_capacity 时不会扩容
        // 所以将第二三种情况放在一起

        void resize(size_t n, char c = '\0')
        {
            if (n <= _size)
            {
                _str[n] = '\0';
                _size = n;
            }
            else
            {
                reserve(n);
                _capacity = n;
                while (_size < n)
                {
                    _str[_size] = c;
                    _size++;
                }
                // 到这里 _size = n
                _str[_size] = '\0';
            }
        }

        void reserve(size_t n)
        {
            if (n > _capacity)
            {
                // _capacity 记录的是需要存储有效数据的个数
                // 所以我们这里要多开一个空间用来记录'\0'
                char* tmp = new char[n + 1];
                strcpy(tmp, _str);
                delete[] _str;
                _str = tmp;

                _capacity = n;
            }

        }



        /

        // access

        char& operator[](size_t index)
        {
            return _str[index];
        }

        const char& operator[](size_t index)const
        {
            return _str[index];
        }



        /

        //relational operators

        bool operator<(const string& s)
        {
            return strcmp(_str, s._str) < 0;
        }

        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)
        {
            return strcmp(_str, s._str) == 0;
        }

        bool operator!=(const string& s)
        {
            return !(*this == s);
        }



        // 返回c在string中第一次出现的位置

        size_t find(char c, size_t pos = 0) const
        {
            assert(pos < _size);
            for (size_t i = pos; i < _size; i++)
            {
                if (_str[i] == c)
                {
                    return i;
                }
            }

            return npos;
        }

        // 返回子串s在string中第一次出现的位置

        size_t find(const char* s, size_t pos = 0) const
        {
            assert(pos < _size);
            char* ret = strstr(_str, s);
            if (ret == nullptr)
            {
                return npos;
            }
            return ret - _str;
        }

        string substr(size_t pos = 0, size_t len = npos) const
        {
            assert(pos < _size);
            string tmp;
            int end = pos + len;
            if (pos + len > _size || len == npos)
            {
                len = _size - pos;
                end = _size;
            }
            
            // 提前开空间防止扩容
            tmp.reserve(len);

            for (int i = pos; i < end; i++)
            {
                tmp += _str[i];
            }

            return tmp;
        }

        

        string& insert(size_t pos, char c)
        {
            assert(pos <= _size);

            if (_size + 1 > _capacity)
            {
                reserve(_capacity == 0 ? 4 : 2 * _capacity);
            }

            // 注意:无符号整形比较是用补码进行比较
            // 当pos = 0,且 i = -1 时 , 0并不比-1大
            // 记得将_size位置上的'\0'也向后移动

            // 版本一 存在问题
            /*for (size_t i = _size; pos <= i; i--)
            {
                _str[i + 1] = _str[i];
            }*/

            // 版本二 将pos转换为有符号整形进行比较
            /*for (int i = _size; (int)pos <= i; i--)
            {
                _str[i + 1] = _str[i];
            }*/

            // 版本三 将 i 置为_size 的后面从后往前移动,防止了0与-1的比较
            for (size_t i = _size + 1; pos < i; i--)
            {
                _str[i] = _str[i - 1];
            }

            _str[pos] = c;
            _size++;

            return *this;
        }

        string& insert(size_t pos, const char* str)
        {
            assert(pos <= _size);

            int len = strlen(str);

            if (_size + len > _capacity)
            {
                reserve(_size + len);
            }

            for (size_t i = _size + len; pos < i; i--)
            {
                _str[i] = _str[i - len];
            }

            strncpy(_str + pos, str, len);
            
            _size+=len;

            return *this;
        }


        string& erase(size_t pos, size_t len = npos)
        {
            assert(pos < _size);

            if (len + pos > _capacity || len == npos)
            {
                _str[pos] = '\0';
                _size = pos;
            }
            else
            {
                size_t begin = len + pos;
                while (begin <= _size)
                {
                    _str[pos] = _str[begin];
                    pos++;
                    begin++;
                }
                _size -= len;
            }
            return *this;
        }

        

    private:
        char* _str;
        size_t _capacity;
        size_t _size;

        const static size_t npos;
    };

    const size_t string::npos = -1;


    ostream& operator<<(ostream& _cout, const string& s)
    {
        for (auto ch : s)
        {
            cout << ch;
        }

        return _cout;
    }

    //istream& operator>>(istream& _cin, string& s)
    //{
    //    // 流插入时需要将string中字符串清除
    //    s.clear();
    //    char ch = 0;
    //    ch = _cin.get();
    //    while (ch != ' ' && ch != '\n')
    //    {
    //        s += ch;
    //        ch = _cin.get();
    //    }
    //    return _cin;
    //}

    istream& operator>>(istream& _cin, string& s)
    {
        // 流插入时需要将string中字符串清除
        s.clear();
        char buff[129] = { 0 };
        char ch = 0;
        ch = _cin.get();
        int i = 0;
        while (ch != ' ' && ch != '\n')
        {
            buff[i] = ch;
            ch = _cin.get();
            if (i == 128)
            {
                s += buff;
                i = 0;
            }
            i++;
        }

        if (i != 0)
        {
            s += buff;
        }
        return _cin;
    }

    // 测试c_str size capacity resize empty
    void test_string1()
    {
        string s("chineseperson");
        cout << s.c_str() << endl;
        cout << s.size() << endl;
        cout << s.capacity() << endl;
        cout << s.empty() << endl;
        cout << endl;

        s.resize(20, 'c');
        cout << s.c_str() << endl;
        cout << s.size() << endl;
        cout << s.capacity() << endl;
        cout << endl;

        s.clear();
        cout << s.c_str() << endl;
        cout << s.size() << endl;
        cout << s.capacity() << endl;
        cout << endl;

        string s1;
        cout << s1.c_str() << endl;
        cout << s1.size() << endl;
        cout << s1.capacity() << endl;
        cout << s1.empty() << endl;
        cout << endl;
    }

    // 测试 push_back append
    void test_string2()
    {
        string s("chineseperson");
        s.push_back('6');
        cout << s.c_str() << endl;
        cout << s.size() << endl;
        cout << s.capacity() << endl;
        cout <<  endl;

        s.append(" hellolllllllllll");
        cout << s.c_str() << endl;
        cout << s.size() << endl;
        cout << s.capacity() << endl;
        cout << endl;

        string s1;
        s1.push_back('6');

        cout << s1.c_str() << endl;
        cout << s1.size() << endl;
        cout << s1.capacity() << endl;
        cout << endl;
    }

    // 测试 +=  operator[]
    void test_string3()
    {
        string s("chineseperson");
        s += '6';
        cout << s.c_str() << endl;
        cout << s.size() << endl;
        cout << s.capacity() << endl;
        cout << endl;

        s += " hellolllllllllll";
        cout << s.c_str() << endl;
        cout << s.size() << endl;
        cout << s.capacity() << endl;
        cout << endl;

        string s1;
        s1 += '6';

        cout << s1.c_str() << endl;
        cout << s1.size() << endl;
        cout << s1.capacity() << endl;
        cout << endl;

        s1[0]++;
        cout << s1.c_str() << endl;
        cout << s1.size() << endl;
        cout << s1.capacity() << endl;
        cout << endl;
    }

    // 测试 迭代器 和 范围for
    void test_string4()
    {
        string s("chineseperson");
        string::iterator it = s.begin();
        while (it != s.end())
        {
            cout << *it << ' ';
            it++;
        }
        cout << endl;

        for (auto ch : s)
        {
            cout <<ch << ' ';
        }
    }

    // 测试流插入流提取
    void test_string5()
    {
        string s;
        cin >> s;
        cout << s << endl;
    }

    // 测试拷贝构造 , 赋值
    void test_string6()
    {
        string s("chineseperson");
        string s1(s);
        cout << s.c_str() << endl;
        cout << s.size() << endl;
        cout << s.capacity() << endl;
        cout << endl;


        cout << s1.c_str() << endl;
        cout << s1.size() << endl;
        cout << s1.capacity() << endl;
        cout << endl;

        string s2("hello");
        cout << s2.c_str() << endl;
        cout << s2.size() << endl;
        cout << s2.capacity() << endl;
        cout << endl;

        s2 = s;
        cout << s.c_str() << endl;
        cout << s.size() << endl;
        cout << s.capacity() << endl;
        cout << endl;
    }

    // 测试string比较
    void test_string7()
    {
        string s("chineseperson");
        string s1(s);
        s1[0]++;
        cout << (s < s1) << endl;
        cout << (s <= s1) << endl;
        cout << (s > s1) << endl;
        cout << (s >= s1) << endl;
        cout << (s != s1) << endl;
        cout << (s == s1) << endl;

    }

    // 测试 find
    void test_string8()
    {
        string s("chineseperson");
        cout << s.find('n') << endl;
        cout << s.find('n', 10) << endl;
        cout << s.find('a') << endl;

        cout << endl;
        cout << s.find("esepe") << endl;

    }

    // 测试insert erase
    void test_string9()
    {
        string s("chineseperson");
        cout << s.c_str() << endl;
        cout << s.size() << endl;
        cout << s.capacity() << endl;
        cout << endl;

        s.insert(0, '6');
        cout << s.c_str() << endl;
        cout << s.size() << endl;
        cout << s.capacity() << endl;
        cout << endl;

        s.insert(s.size(), '6');
        cout << s.c_str() << endl;
        cout << s.size() << endl;
        cout << s.capacity() << endl;
        cout << endl;

        string s1(s);
        s.insert(0, "hello ");
        cout << s.c_str() << endl;
        cout << s.size() << endl;
        cout << s.capacity() << endl;
        cout << endl;

        s.insert(s.size(), " Yeah Yeah Yeah !!");
        cout << s.c_str() << endl;
        cout << s.size() << endl;
        cout << s.capacity() << endl;
        cout << endl;

        string s2(s);
        cout << s2.c_str() << endl;
        cout << s2.size() << endl;
        cout << s2.capacity() << endl;
        cout << endl;

        s2.erase(0, 2);
        cout << s2.c_str() << endl;
        cout << s2.size() << endl;
        cout << s2.capacity() << endl;
        cout << endl;

        s2.erase(15);
        cout << s2.c_str() << endl;
        cout << s2.size() << endl;
        cout << s2.capacity() << endl;
        cout << endl;

        s2.erase(5);
        cout << s2.c_str() << endl;
        cout << s2.size() << endl;
        cout << s2.capacity() << endl;
        cout << endl;
    }
    // 测试 substr
    void test_string10()
    {
        string s("chineseperson");
        cout << s.c_str() << endl;
        cout << s.size() << endl;
        cout << s.capacity() << endl;
        cout << endl;

        string s1 = s.substr(2, 5);
        cout << s1.c_str() << endl;
        cout << s1.size() << endl;
        cout << s1.capacity() << endl;
        cout << endl;

        string s2 = s.substr(2);
        cout << s2.c_str() << endl;
        cout << s2.size() << endl;
        cout << s2.capacity() << endl;
        cout << endl;
        

        string tmp("https://legacy.cplusplus.com/reference/string/string/substr/");
        int i1 = tmp.find(':', 0);
        string ret1 = tmp.substr(0, i1);
        cout << ret1.c_str() << endl;

        int i2 = tmp.find('/', i1 + 3);
        string ret2 = tmp.substr(i1 + 3, i2);
        cout << ret2.c_str() << endl;

        string ret3 = tmp.substr(i2);
        cout << ret3.c_str() << endl;
    }

};


结尾

如果有什么建议和疑问,或是有什么错误,大家可以在评论区中提出。
希望大家以后也能和我一起进步!!🌹🌹
如果这篇文章对你有用的话,希望大家给一个三连支持一下!!🌹🌹

版权声明:本文为博主作者:是阿建吖!原创文章,版权归属原作者,如果侵权,请联系我们删除!

原文链接:https://blog.csdn.net/qq_55401402/article/details/134767692

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2024年4月10日
下一篇 2024年4月10日

相关推荐