string类(使用+模拟实现)(C++)

一、介绍string类

  1. 从C语言字符串开始

在C语言中,字符串是以’\0’结尾的一些字符的集合,为了方便C标准库提供了一些str系列的函数。但是库函数和字符串是分割开的,不符合OOP(面向对象编程)思想,而且底层空间需要自己管理,不注意可能就会出现越界。

所以C++出现了string类。

  1. 了解C++标准库中的string类

string类的出现早于STL

  1. string是表示字符串的类
  2. 该类的接口和常规容器的接口基本相同,并且有专门用来操作string的操作。
  3. 在使用string类时,要包含头文件<string>同时其也在std命名空间当中

二、string类的常用接口

1. 常见构造

(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类对象,空字符串
	string s2("hello");    //用C-string来构造string类对象
	string s3(s2);         //用s2拷贝构造s3
	string s4(10, 'x');    //构造一个10个'x'字符的string对象
}

2. 容量操作

函数名称功能说明
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;
}

//运行结果:
// 5
// 5
// 0
// new1_size:0
// new1_capacity:5
// new2_size:0
// new2_capacity:10
// new3_size:0
// new3_capacity:50
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// new4_size:60
// new4_capacity:100
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// new5_size:70
// new5_capacity:100
  1. clear()只是将string中的有效字符清空,不改变底层空间大小
  2. resize(size_t n)resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时,resize(n)用0来填充多出的元素空间,resize(size_t n, char c)用参数c来填充多出的元素空间
  3. reserve(size_t n = 0)为string预留空间,不改变有效元素个数,当reserve的参数小于string的底层空间总大小时,reserver不会改变容量大小。

3. 访问操作

①访问接口介绍

函数名称功能说明
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;
}


//运行结果:
// i f m m p 
// w o r l d

test2: 迭代器,反向迭代器,范围for

void Test_string()
{
	string s1("hello");
	//迭代器
	string::iterator it = s1.begin();
	while (it != s1.end())
	{
		(*it)++;                  //这里可以更改,下面的const迭代器不能更改
		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;
}


//运行结果:
// i f m m p 
// p m m f i 
// w o r l d 
// d l r o w 
// w o r l d

②迭代器

在上面的例子中,展现了迭代器的一些作用

  1. 分类:
分类迭代器反向迭代器
普通迭代器iteratorreverse_iterator
const迭代器const_iteratorconst_reverse_iterator
  1. 作用:
  1. 迭代器提供一种统一的方式访问和修改容器的数据
  2. 算法通过迭代器去处理容器的数据

4. 增删查改操作

函数名称功能说明
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;
}


//运行结果:
// hello 
// hello   world!
// hello   world! 6666
// xxxxxxxxxxyyxxxxx
// xxxxxxxxxxxxxxx
// erase after:
// hello new !
// hello new kang peng lei!
// 24
// hello new kang peng lei!xxxxx

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;
}

//运行结果:
// hello kang peng lei!
// hello kang peng lei!
// pos2:5
// pos3:24
// pos4:26
// pos5:58
// s4:https
// s5:://legacy.
// Please,  replace  the  vowels  in  this  sentence  by 

5. 非成员函数

函数名称功能说明
operator>>流提取运算符重载
operator<<流插入运算符重载
getline获取一行字符串
relational operators运算符重载(大小比较)

test:

//getline
void Test_string()
{
	string name;
	getline(cin, name);
	cout << "Hello, " << name << "!\n";
}

三、string类的模拟实现

1. 重要方法的实现分析

①构造函数

//带参构造函数
//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];
	memcpy(_str, s._str, s._size);
	_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;
}

赋值运算符重载

小结

因为涉及到开空间,所以构造函数,拷贝构造,赋值运算符重载,析构函数,都需要显示实现

2. 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数组

  1. 写时拷贝(简单介绍)
    写时拷贝

  2. vs2019中的buffer数组
    buffer

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kpl_20

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值