string
- string类“登场”
- string类 - 了解
- string类的常用接口
- 常见构造
- 容量操作
- 访问及遍历操作
- 迭代器
- 分类
- 作用
 
 
- 增删查改操作
- 非成员函数
 
- string类的实现
- string类重要的方法实现分析介绍
- 构造函数
- 拷贝构造函数
- 赋值运算符重载
- 总结
 
- string类整体实现代码
 
- 写时拷贝(了解)
- vs2019中的buffer数组
严格的来说string出现的时候是早于STL
string类“登场”
在C语言中,字符串是以’\0’结尾的一些字符的集合,为了方便C标准库提供了一些str系列的函数。但是库函数和字符串是分割开的,不符合OOP(面向对象编程)思想,而且底层空间需要自己管理,不注意可能就会出现越界。
 为了解决上述问题,所以出现了string类。
string类 - 了解
- string是表示字符串的类
- 该类的接口和常规容器的接口基本相同,并且添加了一些专门用来操作string的常规操作。
string类的常用接口
使用接口时要包含头文件
#include <string>
常见构造
| (constructor)函数名称 | 功能说明 | 
|---|---|
| string() | 构造空的string类对象,即空字符串 | 
| string(const char* s) | 用C-string来构造string类对象 | 
| string(const string& s) | 拷贝构造函数 | 
| string(size_t n, char c) | string类对象中包含n个字符 | 
test:
void Test_string()
{
	string s1;
	string s2("hello");
	string s3(s2);
	string s4(10, 'x');
}
容量操作
| 函数名称 | 功能说明 | 
|---|---|
| size | 返回字符串有效字符长度 | 
| capacity | 返回空间总大小 | 
| empty | 检测字符串释放为空串 | 
| clear | 清空有效字符(改变size,不改变capacity) | 
| reserve | 为字符串开空间 | 
| resize | 将有效字符个数改成n个,多出的空间用字符’c’填充。没有’c’,用0填充 | 
test:
void Test_string()
{
	string s1("hello");
	cout << s1.size() << endl;
	cout << s1.capacity() << endl;
	cout << s1.empty() << endl;
	s1.clear();
	cout << "new1_size:" << s1.size() << endl;
	cout << "new1_capacity:" << s1.capacity() << endl;
	
	s1.reserve(10);
	cout << "new2_size:" << s1.size() << endl;
	cout << "new2_capacity:" << s1.capacity() << endl;
	s1.reserve(50);
	cout << "new3_size:" << s1.size() << endl;
	cout << "new3_capacity:" << s1.capacity() << endl;
	s1.resize(60, 'x');
	cout << s1 << endl;
	cout << "new4_size:" << s1.size() << endl;
	cout << "new4_capacity:" << s1.capacity() << endl;
	
	s1.resize(70);
	cout << s1 << endl;    
	cout << "new5_size:" << s1.size() << endl;
	cout << "new5_capacity:" << s1.capacity() << endl;
}
访问及遍历操作
| 函数名称 | 功能说明 | 
|---|---|
| operator[] | 返回pos位置的字符 | 
| begin + end | 迭代器,左闭右开 | 
| rbegin + rend | 反向迭代器,左闭右开 | 
| 范围for | 遍历方式 | 
test1: operator[]
void Test_string()
{
	string s1("hello");
	//operator[]重载了两个
	//char& operator[] (size_t pos);
	//const char& operator[] (size_t pos) const;
	for (size_t i = 0; i < s1.size(); i++)
	{
		s1[i]++;
		cout << s1[i] << " ";
	}
	cout << endl;
	const string s2("world");
	for (size_t i = 0; i < s2.size(); i++)
	{
		//s2[i]++;     //error
		cout << s2[i] << " ";
	}
	cout << endl;
}
test2: 迭代器,反向迭代器,范围for
void Test_string()
{
	string s1("hello");
	//迭代器
	string::iterator it = s1.begin();
	while (it != s1.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
	
	//反向迭代器
	string::reverse_iterator rit = s1.rbegin();
	while (rit != s1.rend())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;
	//const迭代器
	const string s2("world");
	string::const_iterator c_it = s2.begin();
	while (c_it != s2.end())
	{
		cout << *c_it << " ";
		++c_it;
	}
	cout << endl;
	//const反向迭代器
	string::const_reverse_iterator c_rit = s2.rbegin();
	while (c_rit != s2.rend())
	{
		cout << *c_rit << " ";
		++c_rit;
	}
	cout << endl;
	//范围for
	for (auto ch : s2)
	{
		cout << ch << " ";
	}
	cout << endl;
}
迭代器
在上面的例子中,展现了迭代器的一些作用
分类
| 分类 | 迭代器 | 反向迭代器 | 
|---|---|---|
| 普通迭代器 | iterator | reverse_iterator | 
| const迭代器 | const_iterator | const_reverse_iterator | 
作用
- 迭代器提供一种统一的方式访问和修改容器的数据
- 算法通过迭代器去处理容器的数据
增删查改操作
| 函数名称 | 功能说明 | 
|---|---|
| push_back | 尾插字符 | 
| append | 在字符串后追加字符串 | 
| operator+= | 追加字符串str | 
| c_str | 返回C格式字符串 | 
| erase | 删除 | 
| insert | 插入 | 
| assign | 将内容分配给字符串 | 
| find + npos | 从pos位置开始往后找字符,返回该字符在字符串中的位置 | 
| rfind | 从pos位置开始往前找字符,返回该字符在字符串中的位置 | 
| substr | 在str中从pos位置开始,截取n个字符,然后返回 | 
test1: 增删改操作
void Test_string()
{
	string s1 = "hello";
	//void push_back (char c);
	s1.push_back(' ');
	cout << s1 << endl;
	//append
	//string& append(size_t n, char c);
	s1.append(2, ' ');
	//string& append(const char* s, size_t n);
	s1.append("world!", 6);
	cout << s1.c_str() << endl;
	//operator+=
	s1 += " 6666";
	cout << s1.c_str() << endl;
	//assign
	s1.assign("xxxxxxxxxxyyxxxxx");
	cout << s1 << endl;
	//erase
	//string& erase (size_t pos = 0, size_t len = npos);
	//从第10个位置开始删除两个字符
	s1.erase(10, 2);
	cout << s1 << endl;
	//全部删除
	s1.erase();
	cout << "erase after:" << s1 << endl;
	//insert
	s1.insert(0, "hello new !");
	cout << s1 << endl;
	//从s1第10个位置开始插入字符串的13个字符
	s1.insert(10, "kang peng lei ....", 13);
	cout << s1 << endl;
	cout << s1.size() << endl;
	s1.insert(s1.size(), 5, 'x');
	cout << s1 << endl;
}
test2: 查找和substr
void Test_string()
{
	string s1("hello kang peng lei!");
	//c_str
	char* c_s1 = new char[s1.size() + 1];
	strcpy(c_s1, s1.c_str());
	cout << s1.c_str() << endl;
	cout << c_s1 << endl;
	delete[] c_s1;
	//find
	string s2("https://legacy.cplusplus.com/reference/string/string/find/:");
	//从第3个数开始匹配
	size_t n2 = s2.find("://", 3);
	cout << "pos2:" << n2 << endl;
	string s3(".com/");
	//从s2最开始的地方开始匹配s3
	size_t n3 = s2.find(s3);
	cout << "pos3:" << n3 << endl;
	//从s2第2个位置匹配"om/re"的前三个字母
	size_t n4 = s2.find("om/re", 2, 3);
	cout << "pos4:" << n4 << endl;
	//从第十个位置匹配':'
	size_t n5 = s2.find(':', 10);
	cout << "pos5:" << n5 << endl;
	//substr
	//string substr(size_t pos = 0, size_t len = npos) const;
	string s4;
	s4 = s2.substr(0, 5);
	cout << "s4:" << s4 << endl;
	//从5开始输出十个字符
	string s5 = s2.substr(5, 10);
	cout << "s5:" << s5 << endl;
	string s6("Please, replace the vowels in this sentence by asterisks.");
	size_t found = s6.find(" ");
	size_t pos = 0;
	//find + npos
	while (found != string::npos)
	{
		cout << s6.substr(pos, found - pos) << " ";
		pos = found;
		found = s6.find(" ", found + 1);
	}
	cout << endl;
}
非成员函数
| 函数名称 | 功能说明 | 
|---|---|
| operator>> | 流提取运算符重载 | 
| operator<< | 流插入运算符重载 | 
| getline | 获取一行字符串 | 
| relational operators | 运算符重载(大小比较) | 
test:
//getline
void Test_string()
{
	string name;
	getline(cin, name);
	cout << "Hello, " << name << "!\n";
}
string类的实现
string类重要的方法实现分析介绍
构造函数
	//带参构造函数
	//string(const char* str)
	//	:_size(strlen(str))
	//	,_capacity(_size + 1)
	//	,_str(new char[_capacity])
	//{
	//	strcpy(_str, str);
	//}
	//默认构造函数
	//string()
	//	:_size(0)
	//	,_capacity(1)
	//	,_str(new char[1])
	//{
	//	_str[0] = '\0';
	//}
	
	//构造函数
	string(const char* str = "")
	{
		assert(str != nullptr);
	
		_size = strlen(str);
		_capacity = _size + 1;
		_str = new char[_capacity];
		memcpy(_str, str, _size + 1);
	}

拷贝构造函数
	//拷贝构造函数
	string(const string& s)
	{
		_str = new char[s._capacity + 1];
		memcpy(_str, s._str, s._size + 1);
		_size = s._size;
		_capacity = s._capacity;
	}
	//现代版本的拷贝构造函数
	//有缺陷"hello\0world" 
	//而且要初始化,不初始化交换给tmp会出问题
	/*string(const string& s)
		:_str(nullptr)
		, _size(0)
		, _capacity(0)
	{
		//有缺陷是因为这里使用字符串拷贝的
		string tmp(s._str);
		swap(tmp);
	}*/

赋值运算符重载
	//运算符重载
	//s1 = s2
	/*string& operator=(const string& s)
	{
		if (this != &s)
		{
			char* tmp = new char[s._size + 1];
			memcpy(tmp, s._str, s._size + 1);
			delete[] _str;
			_str = tmp;
			_size = s._size;
			_capacity = s._capacity;
		}
		return *this;
	}*/
	void swap(string& s)
	{
		std::swap(_str, s._str);
		std::swap(_size, s._size);
		std::swap(_capacity, s._capacity);
	}
	//string& operator=(const string& s)
	//{
	//	if (this != &s)
	//	{
	//		string tmp(s);
	//		
	//		//this->swap(tmp)
	//		swap(tmp);
	//	}
	//	return *this;
	//}
	string& operator=(string tmp)
	{
		swap(tmp);
		return *this;
	}

总结
因为涉及到开空间,所以构造函数,拷贝构造,赋值运算符重载,析构函数,都需要显示实现
string类整体实现代码
#include <iostream>
#include <assert.h>
using namespace std;
namespace kpl
{
	class string
	{
	public:
		const static size_t npos;
		//迭代器和const迭代器
		typedef char* iterator;
		typedef const char* const_iterator;
		iterator begin()
		{
			return _str;
		}
		iterator end()
		{
			return _str + _size;
		}
		const_iterator begin() const
		{
			return _str;
		}
		const_iterator end() const
		{
			return _str + _size;
		}
		带参构造函数
		//string(const char* str)
		//	:_size(strlen(str))
		//	,_capacity(_size + 1)
		//	,_str(new char[_capacity])
		//{
		//	strcpy(_str, str);
		//}
		默认构造函数
		//string()
		//	:_size(0)
		//	,_capacity(1)
		//	,_str(new char[1])
		//{
		//	_str[0] = '\0';
		//}
		//构造函数
		string(const char* str = "")
		{
			assert(str != nullptr);
			_size = strlen(str);
			_capacity = _size + 1;
			_str = new char[_capacity];
			memcpy(_str, str, _size + 1);
		}
		//拷贝构造函数
		string(const string& s)
		{
			_str = new char[s._capacity + 1];
			memcpy(_str, s._str, s._size + 1);
			_size = s._size;
			_capacity = s._capacity;
		}
		//现在版本的拷贝构造函数
		//有缺陷"hello\0world" 
		//而且要初始化,不初始化交换给tmp会出问题
		/*string(const string& s)
			:_str(nullptr)
			, _size(0)
			, _capacity(0)
		{
			//有缺陷是因为这里使用字符串拷贝的
			string tmp(s._str);
			swap(tmp);
		}*/
		//运算符重载
		//s1 = s2
		/*string& operator=(const string& s)
		{
			if (this != &s)
			{
				char* tmp = new char[s._size + 1];
				memcpy(tmp, s._str, s._size + 1);
				delete[] _str;
				_str = tmp;
				_size = s._size;
				_capacity = s._capacity;
			}
			return *this;
		}*/
		void swap(string& s)
		{
			std::swap(_str, s._str);
			std::swap(_size, s._size);
			std::swap(_capacity, s._capacity);
		}
		//string& operator=(const string& s)
		//{
		//	if (this != &s)
		//	{
		//		string tmp(s);
		//		
		//		//this->swap(tmp)
		//		swap(tmp);
		//	}
		//	return *this;
		//}
		string& operator=(string tmp)
		{
			swap(tmp);
			return *this;
		}
		//析构函数
		~string()
		{
			delete[] _str;
			_str = nullptr;
			_size = 0;
			_capacity = 0;
		}
		//返回一个c类型的常量字符串
		const char* c_str() const
		{
			return _str;
		}
		size_t capacity() const
		{
			return _capacity;
		}
		size_t size() const
		{
			return _size;
		}
		//重载[]
		char& operator[](size_t pos)
		{
			assert(pos < _size);
			return _str[pos];
		}
		const char& operator[](size_t pos) const
		{
			assert(pos < _size);
			return _str[pos];
		}
		//扩容
		void reserve(size_t n)
		{
			if (n > _capacity)
			{
				char* tmp = new char[n + 1];
				memcpy(tmp, _str, _size + 1);
				delete[] _str;
				_str = tmp;
				_capacity = n + 1;
			}
		}
		void resize(size_t n, char ch = '\0')
		{
			if (n < _size)
			{
				_size = n;
				_str[_size] = '\0';
			}
			else
			{
				//扩容
				reserve(n);
				for (size_t i = _size; i < n; i++)
				{
					_str[i] = ch;
				}
				_size = n;
				_str[_size] = '\0';
			}
		}
		void push_back(char ch)
		{
			if (_size == _capacity - 1)
			{
				reserve(_capacity == 1 ? 4 : 2 * _capacity);
			}
			_str[_size] = ch;
			++_size;
			_str[_size] = '\0';
		}
		void append(const char* str)
		{
			size_t len = strlen(str);
			if (_size + len >= _capacity)
			{
				reserve(_size + len);
			}
			memcpy(_str + _size, str, len);
			_size += len;
			_str[_size] = '\0';
		}
		string& operator+=(char ch)
		{
			push_back(ch);
			return *this;
		}
		string& operator+=(const char* str)
		{
			append(str);
			return *this;
		}
		void insert(size_t pos, size_t n, char ch)
		{
			assert(pos < _size);
			if (n + _size > _capacity - 1)
			{
				reserve(n + _size);
			}
			//挪动数据
			//第一种方法
			/*int end = _size;
			while (end >= (int)pos)
			{
				_str[end + n] = _str[end];
				--end;
			}*/
			//第二种方法
			/*size_t end = _size;
			while (end >= pos && end != npos)
			{
				_str[end + n] = _str[end];
				--end;
			}
			for (size_t i = 0; i < n; i++)
			{
				_str[i + pos] = ch;
			}
			_size += n;*/
			//第三种方法
			size_t end = _size + n;
			while (end >= pos + n)
			{
				_str[end] = _str[end - n];
				--end;
			}
			for (size_t i = 0; i < n; i++)
			{
				_str[i + pos] = ch;
			}
			_size += n;
		}
		void insert(size_t pos, const char* str)
		{
			assert(pos <= _size);
			size_t len = strlen(str);
			if (_size + len > _capacity - 1)
			{
				reserve(len + _size);
			}
			size_t end = _size + len;
			while (end >= pos + len)
			{
				_str[end] = _str[end - len];
				--end;
			}
			for (size_t i = 0; i < len; i++)
			{
				_str[i + pos] = str[i];
			}
			_size += len;
		}
		void erase(size_t pos, size_t len = npos)
		{
			assert(pos <= _size);
			if (len == npos || pos + len >= _size)
			{
				_str[pos] = '\0';
				_size = pos;
			}
			else
			{
				size_t end = pos + len;
				while (end <= _size)
				{
					_str[pos++] = _str[end++];
				}
				_size -= len;
			}
		}
		size_t find(char ch, size_t pos = 0) const
		{
			assert(pos < _size);
			for (size_t i = pos; i < _size; i++)
			{
				if (_str[i] == ch)
				{
					return i;
				}
			}
			return npos;
		}
		size_t find(const char* str, size_t pos = 0) const
		{
			assert(pos < _size);
			const char* ptr = strstr(_str + pos, str);
			return ptr == nullptr ? npos : ptr - _str;
		}
		string substr(size_t pos = 0, size_t len = npos) const
		{
			assert(pos < _size);
			size_t n = len;
			if (len == npos || pos + len > _size)
			{
				n = _size - pos;
			}
			string tmp;
			tmp.reserve(n);
			//i从开始到结束要有n个数据加到tmp所以终止条件是pos+n
			for (size_t i = pos; i < pos + n; i++)
			{
				tmp += _str[i];
			}
			return tmp;
		}
		void clear()
		{
			_str[0] = '\0';
			_size = 0;
		}
		//运算符重载 < 第一种写法
		bool operator<(const string& s) const
		{
			size_t n1 = 0;
			size_t n2 = 0;
			while (n1 < _size && n2 < s._size)
			{
				if (_str[n1] < s._str[n2])
				{
					return true;
				}
				else if (_str[n1] > s._str[n2])
				{
					return false;
				}
				else
				{
					n1++;
					n2++;
				}
			}
			return n1 == _size && n2 != s._size;
			//return _size < s._size;
		}
		//第二种写法
		/*bool operator<(const string& s) const
		{
			int ret = memcmp(_str, s._str, _size < s._size ? _size : s._size);
			return ret == 0 ? _size < s._size : ret < 0;
		}*/
		bool operator==(const string& s) const
		{
			return _size == s._size && memcmp(_str, s._str, _size) == 0;
		}
		
		bool operator<=(const string& s) const
		{
			return *this < s || *this == s;
		}
		bool operator>(const string& s) const
		{
			return !(*this <= s);
		}
		bool operator>=(const string& s) const
		{
			return !(*this < s);
		}
		bool operator!=(const string & s) const
		{
			return !(*this == s);
		}
	private:
		size_t _size;
		size_t _capacity;
		char* _str;
	};
	const size_t string::npos = -1;
	//流插入和流提取运算符重载
	ostream& operator<<(ostream& _cout, const string& s)
	{
		for (auto e : s)
		{
			_cout << e;
		}
		return _cout;
	}
	istream& operator>>(istream& _cin, string& s)
	{
		s.clear();
		//读取一个字符
		char ch = _cin.get();
		while (ch == ' ' || ch == '\n')
		{
			ch = _cin.get();
		}
		//节约空间
		char buf[128];
		int i = 0;
		while (ch != ' ' && ch != '\n')
		{
			buf[i++] = ch;
			if (i == 127)
			{
				buf[i] = '\0';
				s += buf;
				i = 0;
			}
			ch = _cin.get();
		}
		if (i != 0)
		{
			buf[i] = '\0';
			s += buf;
		}
		return _cin;
	}
}
写时拷贝(了解)

vs2019中的buffer数组




















