string类【万字详解,包括认识,介绍,使用,模拟实现】

一、标准库中的string类

1.1 string类的常用接口说明

1.1.1 string类对象的常见构造

在这里插入图片描述

举例:

void Teststring()
{
string s1; // 构造空的string类对象s1
string s2("hello bit"); // 用C格式字符串构造string类对象s2
string s3(s2); // 拷贝构造s3
}

1.1.2. string类对象的容量操作

函数名称 功能说明
size(重点): 返回字符串有效字符长度
length :返回字符串有效字符长度
capacity :返回空间总大小
empty (重点): 检测字符串释放为空串,是返回true,否则返回false
clear (重点) :清空有效字符
reserve (重点): 为字符串预留空间**
resize (重点) :将有效字符的个数该成n个,多出的空间用字符c填充

举例:

// size/clear/resize
void Teststring1()
{
// 注意:string类对象支持直接用cin和cout进行输入和输出
string s("hello, bit!!!");
cout << s.size() << endl;
cout << s.length() << endl;
cout << s.capacity() << endl;
cout << s <<endl;
// 将s中的字符串清空,注意清空时只是将size清0,不改变底层空间的大小
s.clear();
cout << s.size() << endl;
cout << s.capacity() << endl;
// 将s中有效字符个数增加到10个,多出位置用'a'进行填充
// “aaaaaaaaaa”
s.resize(10, 'a');
cout << s.size() << endl;
cout << s.capacity() << endl;
// 将s中有效字符个数增加到15个,多出位置用缺省值'\0'进行填充
// "aaaaaaaaaa\0\0\0\0\0"
// 注意此时s中有效字符个数已经增加到15个
s.resize(15);
cout << s.size() << endl;
cout << s.capacity() << endl;
cout << s << endl;
// 将s中有效字符个数缩小到5个
s.resize(5);
cout << s.size() << endl;
cout << s.capacity() << endl;
cout << s << endl;
}
//================================================================================
====
void Teststring2()
{
string s;
// 测试reserve是否会改变string中有效元素个数
s.reserve(100);
cout << s.size() << endl;
cout << s.capacity() << endl;
// 测试reserve参数小于string的底层空间大小时,是否会将空间缩小
s.reserve(50);
cout << s.size() << endl;
cout << s.capacity() << endl;
}
// 利用reserve提高插入数据的效率,避免增容带来的开销
//================================================================================
====
void TestPushBack()
{
string s;
size_t sz = s.capacity();
cout << "making s grow:\n";
for (int i = 0; i < 100; ++i)
{
s.push_back('c');
if (sz != s.capacity())
{
sz = s.capacity();
cout << "capacity changed: " << sz << '\n';
}
}
}
void TestPushBackReserve()
{
string s;
s.reserve(100);
size_t sz = s.capacity();
cout << "making s grow:\n";
for (int i = 0; i < 100; ++i)
{
s.push_back('c');
if (sz != s.capacity())
{
sz = s.capacity();
cout << "capacity changed: " << sz << '\n';
}
}
}

注意:

  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不会改变容量大小。

1.1.3. string类对象的访问及遍历操作

在这里插入图片描述
举例:

void Teststring()
{
string s1("hello Bit");
const string s2("Hello Bit");
cout<<s1<<" "<<s2<<endl;
cout<<s1[0]<<" "<<s2[0]<<endl;
s1[0] = 'H';
cout<<s1<<endl;
// s2[0] = 'h'; 代码编译失败,因为const类型对象不能修改
}
void Teststring()
{
string s("hello Bit");
// 3种遍历方式:
// 需要注意的以下三种方式除了遍历string对象,还可以遍历是修改string中的字符,
// 另外以下三种方式对于string而言,第一种使用最多
// 1. for+operator[]
for(size_t i = 0; i < s.size(); ++i)
cout<<s[i]<<endl;
// 2.迭代器
string::iterator it = s.begin();
while(it != s.end())
{
cout<<*it<<endl;
++it;
}
string::reverse_iterator rit = s.rbegin();
while(rit != s.rend())
cout<<*rit<<endl;
// 3.范围for
for(auto ch : s)
    cout<<ch<<endl;
}

1.1.4 string类对象的修改操作

push_back :在字符串后尾插字符c
append :在字符串后追加一个字符串
operator+= (重点): 在字符串后追加字符串str
c_str(重点) :返回C格式字符串
find + npos(重点): 从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置
rfind :从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置
substr :在str中从pos位置开始,截取n个字符,然后将其返回
举例:

void Teststring()
{
string str;
str.push_back(' '); // 在str后插入空格
str.append("hello"); // 在str后追加一个字符"hello"
str += 'b'; // 在str后追加一个字符'b'
str += "it"; // 在str后追加一个字符串"it"
cout<<str<<endl;
cout<<str.c_str()<<endl; // 以C语言的方式打印字符串
// 获取file的后缀
string file1("string.cpp");
size_t pos = file.rfind('.');
string suffix(file.substr(pos, file.size()-pos));
cout << suffix << endl;
// npos是string里面的一个静态成员变量
// static const size_t npos = -1;
// 取出url中的域名
sring url("http://www.cplusplus.com/reference/string/string/find/");
cout << url << endl;
size_t start = url.find("://");
if (start == string::npos)
{
cout << "invalid url" << endl;
return;
}
start += 3;
size_t finish = url.find('/', start);
string address = url.substr(start, finish - start);
cout << address << endl;
// 删除url的协议前缀
pos = url.find("://");
url.erase(0, pos+3);
cout<<url<<endl;
}

注意:

  1. 在string尾部追加字符时,s.push_back© / s.append(1, c) / s += 'c’三种的实现方式差不多,一般
    情况下string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可以连接字符串。
  2. 对string操作时,如果能够大概预估到放多少字符,可以先通过reserve把空间预留好。

1.1.5 string类非成员函数

operator+ :尽量少用,因为传值返回,导致深拷贝效率低
operator>> (重点): 输入运算符重载
operator<< (重点):输出运算符重载
getline (重点) :获取一行字符串
relational operators (重点): 大小比较

1.1.6 vs和g++下string结构的说明

注意:下述结构是在32位平台下进行验证,32位平台下指针占4个字节。

  • vs下string的结构
    string总共占28个字节,内部结构稍微复杂一点,先是有一个联合体,联合体用来定义string中字符串的存储空间:

    • 当字符串长度小于16时,使用内部固定的字符数组来存放。

    • 当字符串长度大于等于16时,从堆上开辟空间。

      union _Bxty
      { // storage for small buffer or pointer to larger one
      	value_type _Buf[_BUF_SIZE];
      	pointer _Ptr;
      	char _Alias[_BUF_SIZE]; // to permit aliasing
      } _Bx;
      

      这种设计也是有一定道理的,大多数情况下字符串的长度都小于16,那string对象创建好之后,内部已经有了16个字符数组的固定空间,不需要通过堆创建,效率高。
      其次:还有一个size_t字段保存字符串长度,一个size_t字段保存从堆上开辟空间总的容量
      最后:还有一个指针做一些其他事情。
      故总共占16+4+4+4=28个字节。
      在这里插入图片描述

  • g++下string的结构
    G++下,string是通过写时拷贝实现的,string对象总共占4个字节,内部只包含了一个指针,该指
    针将来指向一块堆空间,内部包含了如下字段:

    • 空间总大小

    • 字符串有效长度

    • 引用计数

      struct _Rep_base
      {
      	size_type _M_length;
      	size_type _M_capacity;
      	_Atomic_word _M_refcount;
      };
      
    • 指向堆空间的指针,用来存储字符串。

二、string类模拟实现

2.1 string.h

#define _CRT_SECURE_NO_WARNINGS 1
#pragma once
#include<iostream>
#include<assert.h>
using namespace std;

#pragma once

// 实现一个简洁的string,不考虑增删查改
//namespace sk  //名字
//{
//	class string
//	{
//	public:
//		string(const char* str)
//			:_str(new char[strlen(str)+1])
//		{
//			strcpy(_str, str);
//		}
//
//		// 传统写法 -- 本本分分去完成深拷贝
//		// s2(s1)
//		//string(const string& s)
//		//	:_str(new char[strlen(s._str)+1])
//		//{
//		//	strcpy(_str, s._str);
//		//}
//
//		 s1 = s3;
//		 s3 = s3
//		/*string& operator=(const string& s)
//		{
//			if (this != &s)
//			{
//				char* tmp = new char[strlen(s._str) + 1];
//				strcpy(tmp, s._str);
//				delete[] _str;
//				_str = tmp;
//			}
//
//			return *this;
//		}*/
//
//		// 现代写法-- 投机取巧的方式去完成深拷贝
//		// s2(s1)
//		string(const string& s)
//			:_str(nullptr)
//		{
//			string tmp(s._str);
//			swap(_str, tmp._str);
//		}
//
//		// s1 = s3
//		/*string& operator=(const string& s)
//		{
//			if (this != &s)
//			{
//				string tmp(s);
//				swap(_str, tmp._str);
//			}
//
//			return *this;
//		}*/
//
//		string& operator=(string s)
//		{
//			swap(_str, s._str);
//			return *this;
//		}
//
//		~string()
//		{
//			if (_str)
//			{
//				delete[] _str;
//				_str = nullptr;
//			}
//		}
//	private:
//		char* _str;
//	};
//
//	void test_string1()
//	{
//		string s1("hello world");
//		string s2(s1);
//
//		string s3("sort");
//		s1 = s3;
//		s3 = s3;
//	}
//}

namespace sk  //名字
{
	// 增删查改
	class string
	{
	public:
		typedef char* iterator;
		typedef const char* const_iterator;

		const_iterator begin() const
		{
			return _str;
		}

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

		iterator begin()
		{
			return _str;
		}

		iterator end()
		{
			return _str + _size;
		}

		/*string()
			:_str(new char[1])
			, _size(0)
			, _capacity(0)
		{
			_str[0] = '\0';
		}*/

		string(const char* str = "")
			:_size(strlen(str))
			, _capacity(_size)
		{
			_str = new char[_capacity + 1];
			strcpy(_str, str);
		}

		// s2(s1)
		//string(const string& s)
		//	:_size(s._size)
		//	, _capacity(s._capacity)
		//{
		//	_str = new char[_capacity + 1];
		//	strcpy(_str, s._str);
		//}

		 s1 = s3;
		 s3 = s3
		//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;
		//}]

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

		// s2(s1)
		string(const string& s)
			:_str(nullptr)
			, _size(0)
			, _capacity(0)
		{
			string tmp(s._str);
			//this->swap(tmp);
			swap(tmp);
		}

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

		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];
				strcpy(tmp, _str);
				delete[] _str;

				_str = tmp;

				_capacity = n;
			}
		}

		void resize(size_t n, char ch = '\0')
		{
			if (n <= _size)
			{
				_size = n;
				_str[_size] = '\0';
			}
			else
			{
				if (n > _capacity)
				{
					reserve(n);
				}

				memset(_str + _size, ch, n - _size);
				_size = n;
				_str[_size] = '\0';
			}
		}

		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);
			if (_size + len > _capacity)
			{
				reserve(_size + len);
			}

			strcpy(_str + _size, str);
			_size += len;*/

			insert(_size, str);
		}

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

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

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

			return npos;
		}

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

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

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

			/*size_t end = _size;
			while (end >= pos)
			{
			_str[end + 1] = _str[end];
			--end;
			}*/

			/*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 - 1)
			{
				_str[end] = _str[end - len];
				--end;
			}

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

			return *this;
		}

		string& erase(size_t pos = 0, 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;
			}

			return *this;
		}

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

	private:
		char* _str;
		size_t _size;
		size_t _capacity; // 能存储有效字符的空间数,不包含\0
	public:
		static const size_t npos = -1;
	};

	// "abcd"  "abcd"  false
	// "abcd"  "abcde" true
	// "abcde" "abcd"  false 
	bool operator<(const string& s1, const string& s2)
	{
		/*size_t i1 = 0, i2 = 0;
		while (i1 < s1.size() && i2 < s2.size())
		{
			if (s1[i1] < s2[i2])
			{
				return true;
			}
			else if (s1[i1] > s2[i2])
			{
				return false;
			}
			else
			{
				++i1;
				++i2;
			}
		}

		return i2 < s2.size() ? true : false;*/

		return strcmp(s1.c_str(), s2.c_str()) < 0;
	}

	bool operator==(const string& s1, const string& s2)
	{
		return strcmp(s1.c_str(), s2.c_str()) == 0;
	}

	bool operator<=(const string& s1, const string& s2)
	{
		return s1 < s2 || s1 == s2;
	}

	bool operator>(const string& s1, const string& s2)
	{
		return !(s1 <= s2);
	}

	bool operator>=(const string& s1, const string& s2)
	{
		return !(s1 < s2);
	}

	bool operator!=(const string& s1, const string& s2)
	{
		return !(s1 == s2);
	}

	// =
	// << >>
	// ++
	// cout<<s1 -> operator<<(cout, s1)
	ostream& operator<<(ostream& out, const string& s)
	{
		/*for (auto ch : s)
		{
			out << ch;
		}*/

		for (size_t i = 0; i < s.size(); ++i)
		{
			out << s[i];
		}

		//out << s.c_str(); // 不能这么写

		return out;
	}

	istream& operator>>(istream& in, string& s)
	{
		s.clear();

		//char ch = in.get();
		//while (ch != ' ' && ch != '\n')
		//{
		//	s += ch;
		//	ch = in.get();
		//}

		char buff[128] = { '\0' };
		size_t i = 0;
		char ch = in.get();
		while (ch != ' ' && ch != '\n')
		{
			if (i < 127)
			{
				buff[i++] = ch;
			}
			else
			{
				s += buff;
				i = 0;
			}
			ch = in.get();
		}
		if (i >= 0)
		{
			s += buff;
		}
		return in;
	}

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

	void f(const string& s)
	{
		//s[0] = 'x';
		cout << s[0] << endl;
	}

	void test_string1()
	{
		string s1("hello world");
		string s2;
		cout << s1.c_str() << endl;
		cout << s2.c_str() << endl;

		s1[0] = 'x';
		//s1[30];
		for (size_t i = 0; i < s1.size(); ++i)
		{
			cout << s1[i] << " ";
		}
		cout << endl;

		f(s1);
	}

	void test_string2()
	{
		string s1("hello world");

		string::iterator it = s1.begin();
		while (it != s1.end())
		{
			*it += 1;
			++it;
		}

		it = s1.begin();
		while (it != s1.end())
		{
			cout << *it << " ";
			++it;
		}
		cout << endl;

		// 编译时被替换成迭代器
		for (auto e : s1)
		{
			cout << e << " ";
		}
		cout << endl;

		/*auto it = s1.begin();
		while (it != s1.end())
		{
		*it += 1;
		++it;
		}*/
	}

	void test_string3()
	{
		string s1("hello world");
		s1.push_back('@');
		s1.push_back(' ');
		s1.append("hello bit11111111111111111111111111111111");
		cout << s1.c_str() << endl;

		string s2;
		s2 += 'x';
		s2 += "yz 123";
		cout << s2.c_str() << endl;
	}

	void test_string4()
	{
		string s1("hello world");
		s1.insert(0, 'x');
		cout << s1.c_str() << endl;

		s1.insert(0, "abcd");
		cout << s1.c_str() << endl;
	}

	void test_string5()
	{
		/*string s1("helloworld");
		s1.erase(5, 2);
		s1.erase(5, 20);*/

		string s2("hello");
		s2.insert(0, "ab");

		cout << s2.c_str() << endl;

		cout << string::npos << endl;
	}

	void test_string6()
	{
		string s1("abcd");
		string s2("abcd");
		cout << (s1 < s2) << endl;

		string s3("abcd");
		string s4("abcde");
		cout << (s3 < s4) << endl;

		string s5("abcde");
		string s6("abcd");
		cout << (s5 < s6) << endl;
	}

	void test_string7()
	{
		std::string s1("hello");
		cin >> s1;
		cout << s1 << endl;

		//string s1("hello");
		//s1 += '\0';
		//s1 += "world";
		//cout << s1 << endl;
		//cout << s1.c_str() << endl;
	}
}

2.2 string.cpp

#define _CRT_SECURE_NO_WARNINGS 1
#include “string.h”
int main()
{
//sk::test_string1();
//sk::test_string2();
//sk::test_string3();
//sk::test_string4();
//sk::test_string5();
//sk::test_string6();
sk::test_string7();
return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值