文章目录
- 1. 前言
- 2. string类的常用接口
- 2.1 string类对象的常见构造
- 2.2 string类对象的容量操作
- 2.3 string类对象的访问及遍历操作
- 2.4 string类对象的修改操作
- 2.5 string类非成员函数
- 2.6 string四种迭代器类型
- 2.7 string类的insert和erase函数
 
- 3. 浅拷贝和深拷贝
- 4. string类模拟实现
- 5. 结尾
1. 前言
C语言中,字符串是以’\0’结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。所以我们今天来学习C++标准库中的string类。
2. string类的常用接口
2.1 string类对象的常见构造
| (constructor)函数名称 | 功能说明 | 
|---|---|
| string() | 构造空的string类对象,即空字符串 | 
| string(const char* s) | 用C-string来构造string类对象 | 
| string(size_t n, char c) | string类对象中包含n个字符c | 
| string(const string&s) | 拷贝构造函数 | 
void Test1()
{
	string s1;
	//string s2 = "hello world!!!";
	string s2("hello world!!!");
	cout << s1 << endl;
	cout << s2 << endl;
	string s3(s2);
	cout << s3 << endl;
	string s4(s2, 6, 5);
	cout << s4 << endl;
	//第三个参数len大于后面字符长度,有多少拷贝多少拷贝到结尾
	string s5(s2, 6, 15);
	cout << s5 << endl;
	string s6(s2, 6);
	cout << s6 << endl;
	string s7("hello world", 5);
	cout << s7 << endl;
	string s8(100, 'x');
	cout << s8 << endl;
}

2.2 string类对象的容量操作
| 函数名称 | 功能说明 | 
|---|---|
| size | 返回字符串有效字符长度 | 
| length | 返回字符串有效字符长度 | 
| capacity | 返回空间总大小 | 
| empty | 检测字符串释放为空串,是返回true,否则返回false | 
| clear | 清空有效字符 | 
| reserve | 为字符串预留空间 | 
| resize | 将有效字符的个数该成n个,多出的空间用字符c填充 | 
注意:
注意:
1.size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()。
2.clear()只是将string中有效字符清空,不改变底层空间大小。
3.resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时:resize(n)用0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。
4.reserve(size_t res_arg=0):为string预留空间,不改变有效元素个数,当reserve的参数小于string的底层空间总大小时,reserver不会改变容量大小。
2.3 string类对象的访问及遍历操作
| 函数名称 | 功能说明 | 
|---|---|
| operator[] | 返回pos位置的字符,const string类对象调用 | 
| begin+ end | begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器 | 
| rbegin + rend | begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器 | 
| 范围for | C++11支持更简洁的范围for的新遍历方式 | 
void Test3()
{
	string s1("hello world");
	cout << s1[0] << endl;
	s1[0] = 'x';
	cout << s1[0] << endl;
	cout << s1 << endl;
	//遍历s1,每个字符+1
	for (size_t i = 0; i < s1.size(); i++)
	{
		s1[i]++;
	}
	cout << s1 << endl;
	const string s2("world");
	for (size_t i = 0; i < s2.size(); i++)
	{
		//s2[i]++; 失败,const修饰的变量不能修改
		cout << s2[i] << " ";
	}
	cout << endl;
	cout << s2 << endl;
	//cout << s2[6] << endl; 失败,operator[]内部会检查越界访问
}

void Test4()
{
	string s1("hello");
	//iterator迭代器类型,像指针一样的类型,有可能就是指针,也可能不是指针,但用法和指针一样
	string::iterator it = s1.begin();
	while (it != s1.end())
	{
		(*it)++;
		cout << *it << " ";
		it++;
	}
	cout << endl;
	cout << s1 << endl;
	//范围for,自动迭代,自动判断结束
	//依次取s1的每个字符,赋值给ch
	//for (auto ch : s1)
	//{
	//	ch++;//改变不会影响s1
	//	cout << ch << " ";
	//}
	//cout << endl;
	//cout << s1 << endl;
	for (auto& ch : s1)
	{
		ch++;
		cout << ch << " ";
	}
	cout << endl;
	cout << s1 << endl;
	list<int> lt(10, 1);
	list<int>::iterator lit = lt.begin();
	while (lit != lt.end())
	{
		cout << *lit << " ";
		lit++;
	}
	cout << endl;
	for (auto e : lt)
	{
		cout << e << " ";
	}
	cout << endl;
	//范围for底层其实就是迭代器
}

2.4 string类对象的修改操作
| 函数名称 | 功能说明 | 
|---|---|
| push_back | 在字符串后尾插字符c | 
| append | 在字符串后追加一个字符串 | 
| operator+= | 字符串后追加字符串str | 
| c_str | 返回C格式字符串 | 
| find+npos | 从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置 | 
| rfind | 从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置 | 
| substr | 在str中从pos位置开始,截取n个字符,然后将其返回 | 
void Test6()
{
	string s1("hello");
	s1.push_back('-');
	s1.push_back('-');
	s1.append("world");
	cout << s1 << endl;
	string s2("哈哈哈");
	s1 += '@';
	s1 += s2;
	s1 += "!!!";
	cout << s1 << endl;
	s1.append(++s2.begin(), --s2.end());
	cout << s1 << endl;
	//string copy(++s1.begin(), --s1.end());
	string copy(s1.begin() + 5, s1.end() - 5);
	cout << copy << endl;
}

void Test8()
{
	string s1("hello world");
	cout << s1 << endl;
	cout << s1.c_str() << endl;
	s1 += '\0';
	s1 += "hello";
	cout << s1 << endl;//string对象以size为结束的标准
	cout << s1.c_str() << endl;//常量字符串对象以\0为结束的标准
}

void Test9()
{
	string s1("test.cpp");
	//取后缀
	size_t pos = s1.find('.');
	if (pos != string::npos)
	{
		string s2 = s1.substr(pos);
		cout << s2 << endl;
	}
	string s3("test.cpp.txt.zip");
	size_t pos2 = s3.rfind('.');
	if (pos2 != string::npos)
	{
		string s4 = s3.substr(pos2);
		cout << s4 << endl;
	}
}

2.5 string类非成员函数
| 函数名称 | 功能说明 | 
|---|---|
| operator+ | 尽量少用,因为传值返回,导致深拷贝效率低 | 
| operator>> | 输入运算符重载 | 
| operator<< | 输出运算符重载 | 
| getline | 获取一行字符串 | 
| relational operators | 大小比较 | 
void Test10()
{
	string s1("aaabbb");
	string s2("aaabbc");
	cout << (s1 > s2) << endl;
	cout << (s1 < s2) << endl;
}

void Test11()
{
	string s1;
	getline(cin, s1);
	cout << s1 << endl;
}

2.6 string四种迭代器类型
iterator迭代器类型,像指针一样的类型,有可能就是指针,也可能不是指针,但用法和指针一样
string类一共有四种迭代器:
iterator/const_iterator
reverse_iterator/const_reverse_iterator
具体功能如下
void Test4()
{
	string s1("hello");
	//iterator迭代器类型,像指针一样的类型,有可能就是指针,也可能不是指针,但用法和指针一样
	string::iterator it = s1.begin();
	while (it != s1.end())
	{
		(*it)++;
		cout << *it << " ";
		it++;
	}
	cout << endl;
	cout << s1 << endl;
	//范围for,自动迭代,自动判断结束
	//依次取s1的每个字符,赋值给ch
	//for (auto ch : s1)
	//{
	//	ch++;//改变不会影响s1
	//	cout << ch << " ";
	//}
	//cout << endl;
	//cout << s1 << endl;
	for (auto& ch : s1)
	{
		ch++;
		cout << ch << " ";
	}
	cout << endl;
	cout << s1 << endl;
	list<int> lt(10, 1);
	list<int>::iterator lit = lt.begin();
	while (lit != lt.end())
	{
		cout << *lit << " ";
		lit++;
	}
	cout << endl;
	for (auto e : lt)
	{
		cout << e << " ";
	}
	cout << endl;
	//范围for底层其实就是迭代器
}

void PrintString(const string& str)
{
	//auto it = str.begin();
	string::const_iterator it = str.begin();
	while (it != str.end())
	{
		//*it = 'x'; 失败,不能修改const类型的变量
		cout << *it << " ";
		it++;
	}
	cout << endl;
	string::const_reverse_iterator rit = str.rbegin();
	while (rit != str.rend())
	{
		cout << *rit << " ";
		rit++;
	}
	cout << endl;
}
void Test5()
{
	string s1("hello");
	string::reverse_iterator rit = s1.rbegin();
	while (rit != s1.rend())
	{
		cout << *rit << " ";
		rit++;
	}
	cout << endl;
	PrintString(s1);
}

2.7 string类的insert和erase函数
insert:在pos位置,插入字符串或字符,原位置字符串向后挪动。
erase:从pos位置开始,删除后面的n个字符。
void Test7()
{
	string s1("哈 哈 哈");
	for (size_t i = 0; i < s1.size(); i++)
	{
		if (s1[i] == ' ')
		{
			s1.insert(i, "666");
			i += 3;
		}
	}
	cout << s1 << endl;
	for (size_t i = 0; i < s1.size(); i++)
	{
		if (s1[i] == ' ')
		{
			s1.erase(i, 1);
		}
	}
	cout << s1 << endl;
	string str;
	for (size_t i = 0; i < s1.size(); i++)
	{
		if (s1[i] != ' ')
		{
			str += s1[i];
		}
		else
		{
			str += "666";
		}
	}
	cout << str << endl;
}

3. 浅拷贝和深拷贝
浅拷贝:也叫位拷贝,编译器只是将对象中的值拷贝过来。如果对象中管理资源,最后就会导致多个对象共享同一份资源,当一个对象销毁时就会将该资源释放掉,而此时另一些对象不知道该资源已经被放,以为还有效,所以当继续对资源进项操作时,就会发生发生了访问违规。
深拷贝:如果一个类中涉及到资源的管理,其拷贝构造函数、赋值运算符重载以及析构函数必须要显式给出。一般情况都是按照深拷贝方式提供。
4. string类模拟实现
namespace fiora
{
	class string
	{
	public:
		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;
			_str = new char[_capacity + 1];
			strcpy(_str, str);
		}
		// 传统写法
		// s2(s1)
		//string(const string& s)
		//	:_str(new char[s._capacity+1])
		//	, _size(s._size)
		//	, _capacity(s._capacity)
		//{
		//	strcpy(_str, s._str);
		//}
		 s1 = s3
		 s1 = s1
		//string& operator=(const string& s)
		//{
		//	if (this != &s)
		//	{
		//		char* tmp = new char[s._capacity + 1];
		//		strcpy(tmp, s._str);
		//		delete[] _str;
		//		_str = tmp;
		//		_size = s._size;
		//		_capacity = s._capacity;
		//	}
		//	return *this;
		//}
		// 现代写法
		// s2(s1)
		void swap(string& tmp)
		{
			::swap(_str, tmp._str);
			::swap(_size, tmp._size);
			::swap(_capacity, tmp._capacity);
		}
		// s2(s1)
		string(const string& s)
			:_str(nullptr)
			, _size(0)
			, _capacity(0)
		{
			string tmp(s._str);
			swap(tmp); //this->swap(tmp);
		}
		// s1 = s3
		//string& operator=(const string& s)
		//{
		//	if (this != &s)
		//	{
		//		//string tmp(s._str);
		//		string tmp(s);
		//		swap(tmp); // this->swap(tmp);
		//	}
		//	return *this;
		//}
		// s1 = s3
		string& operator=(string s)
		{
			swap(s);
			return *this;
		}
		~string()
		{
			delete[] _str;
			_str = nullptr;
			_size = _capacity = 0;
		}
		const char* c_str() const
		{
			return _str;
		}
		size_t size() const
		{
			return _size;
		}
		size_t capacity() const
		{
			return _capacity;
		}
		const char& operator[](size_t pos) const
		{
			assert(pos < _size);
			return _str[pos];
		}
		char& operator[](size_t pos)
		{
			assert(pos < _size);
			return _str[pos];
		}
		void reserve(size_t n)
		{
			if (n > _capacity)
			{
				char* tmp = new char[n + 1];
				strcpy(tmp, _str);
				delete[] _str;
				_str = tmp;
				_capacity = n;
			}
		}
		void push_back(char ch)
		{
			// 满了就扩容
			/*if (_size == _capacity)
			{
				reserve(_capacity == 0 ? 4 : _capacity * 2);
			}
			_str[_size] = ch;
			++_size;
			_str[_size] = '\0';*/
			insert(_size, ch);
		}
		void append(const char* str)
		{
			//size_t len = strlen(str);
			 满了就扩容
			 _size + len  8  18  10  
			//if (_size + len > _capacity)
			//{
			//	reserve(_size+len);
			//}
			//strcpy(_str + _size, str);
			strcat(_str, str); 需要找\0,效率低
			//_size += len;
			insert(_size, str);
		}
		string& operator+=(char ch)
		{
			push_back(ch);
			return *this;
		}
		string& operator+=(const char* str)
		{
			append(str);
			return *this;
		}
		string& insert(size_t pos, char ch)
		{
			assert(pos <= _size);
			// 满了就扩容
			if (_size == _capacity)
			{
				reserve(_capacity == 0 ? 4 : _capacity * 2);
			}
			 挪动数据
			//int end = _size;
			//while (end >= (int)pos)
			//{
			//	_str[end + 1] = _str[end];
			//	--end;
			//}
			size_t end = _size + 1;
			while (end > pos)
			{
				_str[end] = _str[end - 1];
				--end;
			}
			_str[pos] = ch;
			++_size;
			return *this;
		}
		string& insert(size_t pos, const char* str)
		{
			assert(pos <= _size);
			size_t len = strlen(str);
			if (_size + len > _capacity)
			{
				reserve(_size + len);
			}
			// 挪动数据
			size_t end = _size + len;
			while (end >= pos + len)
			{
				_str[end] = _str[end - len];
				--end;
			}
			strncpy(_str + pos, str, len);
			_size += len;
			return *this;
		}
		void erase(size_t pos, size_t len = npos)
		{
			assert(pos < _size);
			if (len == npos || pos + len >= _size)
			{
				_str[pos] = '\0';
				_size = pos;
			}
			else
			{
				strcpy(_str + pos, _str + pos + len);
				_size -= len;
			}
		}
		size_t find(char ch, size_t pos = 0) const;
		size_t find(const char* sub, size_t pos = 0) const;
		bool operator>(const string& s) const;
		bool operator==(const string& s) const;
		bool operator>=(const string& s) const;
		bool operator<=(const string& s) const;
		bool operator<(const string& s) const;
		bool operator!=(const string& s) const;
	private:
		size_t _capacity;
		size_t _size;
		char* _str;
		// const static 语法特殊处理
		// 直接可以当成定义初始化
		const static size_t npos = -1;
	};
	ostream& operator<<(ostream& out, const string& s)
	{
		for (size_t i = 0; i < s.size(); ++i)
		{
			out << s[i];
		}
		return out;
	}
	istream& operator>>(istream& in, string& s)
	{
		// 输入字符串很长,不断+=,频繁扩容,效率很低
		char ch;
		//in >> ch;
		ch = in.get();
		while (ch != ' ' && ch != '\n')
		{
			s += ch;
			ch = in.get();
		}
		return in;
	}
	//size_t string::npos = -1;
	void test_string1()
	{
		/*std::string s1("hello world");
		std::string s2;*/
		string s1("hello world");
		string s2;
		cout << s1.c_str() << endl;
		cout << s2.c_str() << endl;
		for (size_t i = 0; i < s1.size(); ++i)
		{
			cout << s1[i] << " ";
		}
		cout << endl;
		for (size_t i = 0; i < s1.size(); ++i)
		{
			s1[i]++;
		}
		for (size_t i = 0; i < s1.size(); ++i)
		{
			cout << s1[i] << " ";
		}
		cout << endl;
	}
	void test_string2()
	{
		string s1("hello world");
		string::iterator it = s1.begin();
		while (it != s1.end())
		{
			cout << *it << " ";
			++it;
		}
		cout << endl;
		it = s1.begin();
		while (it != s1.end())
		{
			*it += 1;
			++it;
		}
		cout << endl;
		for (auto ch : s1)
		{
			cout << ch << " ";
		}
		cout << endl;
	}
	void test_string3()
	{
		string s1("hello world");
		string s2(s1);
		cout << s1.c_str() << endl;
		cout << s2.c_str() << endl;
		s2[0] = 'x';
		cout << s1.c_str() << endl;
		cout << s2.c_str() << endl;
		string s3("111111111111111111111111111111");
		s1 = s3;
		cout << s1.c_str() << endl;
		cout << s3.c_str() << endl;
		s1 = s1;
		cout << s1.c_str() << endl;
		cout << s3.c_str() << endl;
	}
	void test_string4()
	{
		string s1("hello world");
		string s2("xxxxxxx");
		s1.swap(s2);
		swap(s1, s2);
	}
	void test_string5()
	{
		string s1("hello");
		cout << s1.c_str() << endl;
		s1.push_back('x');
		cout << s1.c_str() << endl;
		cout << s1.capacity() << endl;
		s1 += 'y';
		s1 += 'z';
		s1 += 'z';
		s1 += 'z';
		s1 += 'z';
		s1 += 'z';
		s1 += 'z';
		cout << s1.c_str() << endl;
		cout << s1.capacity() << endl;
	}
	void test_string6()
	{
		string s1("hello");
		cout << s1.c_str() << endl;
		s1 += ' ';
		s1.append("world");
		s1 += "bit hello";
		cout << s1.c_str() << endl;
		s1.insert(5, '#');
		cout << s1.c_str() << endl;
		s1.insert(0, '#');
		cout << s1.c_str() << endl;
	}
	void test_string7()
	{
		string s1("hello");
		cout << s1.c_str() << endl;
		s1.insert(2, "world");
		cout << s1.c_str() << endl;
		s1.insert(0, "world ");
		cout << s1.c_str() << endl;
	}
	void test_string8()
	{
		string s1("hello");
		s1.erase(1, 10);
		cout << s1.c_str() << endl;
		string s2("hello");
		s2.erase(1);
		cout << s2.c_str() << endl;
		string s3("hello");
		s3.erase(1, 2);
		cout << s3.c_str() << endl;
	}
	void test_string9()
	{
		/*	string s1;
			cin >> s1;
			cout << s1 << endl;*/
		string s1("hello");
		cout << s1 << endl;
		cout << s1.c_str() << endl;
		s1 += '\0';
		s1 += "world";
		cout << s1 << endl;
		cout << s1.c_str() << endl;
		string s3, s4;
		cin >> s3 >> s4;
		cout << s3 << s4 << endl;
	}
}
5. 结尾
C++string类的基本概念我们就学习到这里,在常规工作中,为了简单、方便、快捷,基本都使用string类,很少有人去使用C库中的字符串操作函数。实际上string类有100多种接口,但我们没办法全部实现出来,而且也有很多是几乎用不到的接口,本文主要介绍的是常用及常见的接口。
 最后,感谢各位大佬的耐心阅读和支持,觉得本篇文章写的不错的朋友可以三连关注支持一波,如果有什么问题或者本文有错误的地方大家可以私信我,也可以在评论区留言讨论,再次感谢各位。




![[极客大挑战 2019]HardSQL1](https://img-blog.csdnimg.cn/img_convert/371f807c75ee420b9af63daf209682b8.png)













