string

  • 标准库中的string类
  • string类的模拟实现

1.标准库中的string类

1.1 string类的介绍

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

注意:在使用string类时,必须包含头文件以及using namespace std;

1.2 string的常用接口说明
1.string类对象的常见构造
在这里插入图片描述

void TestString()
{
	string s1; // 构造空的string类对象s1
	string s2("hello bit"); // 用C格式字符串构造string类对象s2
	string s3(10, 'a'); // 用10个字符'a'构造string类对象s3
	string s4(s2); // 拷贝构造s4
	string s5(s3, 5); // 用s3中前5个字符构造string对象s5
}

  1. string类对象的容量操作
    在这里插入图片描述
// size/length/clear/resize
void TestString1()
{
	// 注意:string类对象支持直接用cin和cout进行输入和输出
	string s("hello, bit!!!");
	cout << s.length();
	cout << s.size() << 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;
}
//====================================================================================
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;
}

注意:

  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的底层空间总大小时,reserve不会改变容量大小。
  1. 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;

	for (size_t i = 0; i < s1.size(); ++i)
	{
		cout << s1[i] << endl;
	}

	// s2[0] = 'h'; 代码编译失败,因为const类型对象不能修改
}
  1. string类对象的修改操作

在这里插入图片描述

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;
}
// 利用reserve提高插入数据的效率,避免增容带来的开销
//=============================================================================

void TestPushBack()
{
	string s;
	size_t sz = s.capacity();
	cout << "making s grow:\n";
	for (int i = 0; i < 100; ++i)
	{
		s += 'c';
		if (sz != s.capacity())
		{
			sz = s.capacity();
			cout << "capacity changed: " << sz << '\n';
		}
	}
}
void TestPushBack_P()
{
	string s;
	s.reserve(100);
	size_t sz = s.capacity();

	cout << "making s grow:\n";
	for (int i = 0; i < 100; ++i)
	{
		s += 'c';
		if (sz != s.capacity())
		{
			sz = s.capacity();
			cout << "capacity changed: " << sz << '\n';
		}
	}
}

注意:

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

在这里插入图片描述
2. string类的模拟实现
2.1 浅拷贝

class String
{
public:
	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 bit!!!");
	String s2(s1);
}

在这里插入图片描述

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

2.2 深拷贝
如果一个类中涉及到资源的管理,其拷贝构造函数、赋值运算符重载以及析构函数必须要显式给出。一般情况都是按照深拷贝方式提供。
在这里插入图片描述
2.3 传统版写法的String类

class String
{
public:
	String(const char* str = "")
	{
		// 构造string类对象时,如果传递nullptr指针,认为程序非法,此处断言下
		if (nullptr == str)
		{
			assert(false);
			return;
		}

		_str = new char[strlen(str) + 1];
		strcpy(_str, str);
	}

	String(const String& s)
		: _str(new char[strlen(s._str) + 1])
	{
		strcpy(_str, s._str);
	}

	String& operator=(const String& s)
	{
		if (this != &s)
		{
			char* pStr = new char[strlen(s._str) + 1];
			strcpy(pStr, s._str);
			delete[] _str;
			_str = pStr;
		}

		return *this;
	}

	~String()
	{
		if (_str)
		{
			delete[] _str;
			_str = nullptr;
		}
	}

private:
	char* _str;
};

2.4 现代版写法的String类

class String
{
	
public:
	String(const char* str = "")
	{
		if (nullptr == str)
			str = "";

		_str = new char[strlen(str) + 1];
		strcpy(_str, str);
	}

	String(const String& s)
		: _str(nullptr)
	{
		String strTmp(s._str);
		swap(_str, strTmp);
	}

	// 对比下和上面的赋值那个实现比较好?
	String& operator=(String s)
	{
		swap(_str, s._str);
		return *this;
	}

	/*
	String& operator=(const String& s)
	{
	if(this != &s)
	{
	String strTmp(s);
	swap(_str, strTmp._str);
	}

	return *this;
	}
	*/

	~String()
	{
		if (_str)
		{
			delete[] _str;
			_str = nullptr;
		}
	}

private:
	char* _str;
};

2.5 写时拷贝
写时拷贝就是一种拖延症,是在浅拷贝的基础之上增加了引用计数的方式来实现的。
引用计数:用来记录资源使用者的个数。在构造时,将资源的计数给成1,每增加一个对象使用该资源,就给计数增加1,当某个对象被销毁时,先给该计数减1,然后再检查是否需要释放资源,如果计数为1,说明该对象时资源的最后一个使用者,将该资源释放;否则就不能释放,因为还有其他对象在使用该资源。

2.6 string类的模拟实现

#define _CRT_SECURE_NO_WARNINGS 

#pragma once
#include<iostream>
#include<assert.h>
#include<string>
#include<algorithm>
using namespace std;
	class String
	{
	public:
		typedef char* iterator;
		iterator begin()
		{
			return _str;
		}
		iterator end()
		{
			return _str + _size;
		}
//1.string类对象的常见构造
		//构造函数
		String(const char* str = "")
		{
			if (nullptr == str)
			{
				assert(false);
				return;
			}
			_size = strlen(str);
			_capacity = _size;
			_str = new char[_capacity + 1];//加1保存'\0'
			strcpy(_str, str);
		}
		//拷贝构造
		String(const String& s)
			:_str(new char[s._capacity + 1])
			, _size(s._size)
			, _capacity(s._capacity)
		{
			strcpy(_str, s._str);
		}
		//赋值操作
		String& operator=(const String& s)
		{
			if (this != &s)
			{
				String tmp(s._str);
				swap(_str, tmp._str);
			}
			return *this;
		}
		//析构函数
		~String()
		{
			if (_str)
			{
				delete[] _str;
				_str = nullptr;
				_size = 0;
				_capacity = 0;
			}
		}
		char* c_str()
		{
			return _str;
		}
		//modify修改操作
		void PushBack(char ch)//尾插一个字符
		{
			if (_size == _capacity)
			{
				Reserve(_capacity * 2);
			}
			_str[_size++] = ch;
			_str[_size] = '\0';
		}
		void Append(size_t n, char c)//追加n个字符c
		{
			for (size_t i = 0; i < n; ++i)
			{
				PushBack(c);
			}
		}
		void Append(const char* str)//追加字符串
		{
			for (size_t i = 0; i < strlen(str); ++i)
			{
				PushBack(str[i]);
			}
		}
		String& operator+=(char ch)//加一个字符
		{
			PushBack(ch);
			return *this;
		}
		String& operator+=(const char* str)//加一个字符串
		{
			Append(str);
			return *this;
		}
		String& Insert(size_t pos, char ch)
		{
			assert(pos < _size);
			int end = _size;
			if (_size == _capacity)
			{
				Reserve(_capacity * 2);
			}
			for (end = _size; end >= (int)pos; --end)
			{
				_str[end + 1] = _str[end];
			}
			_str[pos] = ch;
			++_size;
			_str[_size] = '\0';
			return *this;
		}
		String& Insert(size_t pos, const char* str)
		{
			assert(pos < _size);
			size_t len = strlen(str);
			if (len + _size>_capacity)
			{
				Reserve(len + _size);
			}
			for (size_t i = _size + len; i > pos; --i)
			{
				_str[i] = _str[i - len];
			}
			for (size_t j = 0; j < len; ++j)
			{
				_str[pos + j] = str[j];
				++_size;
			}
			_str[_size] = '\0';
			return *this;
		}
		String& Erase(size_t pos, size_t len)
		{
			if (pos + len >= _size - 1)
			{
				_str[pos] = '\0';
				_size = pos;
			}
			else
			{
				strcpy(_str + pos, _str + pos + len);
			}
			_size -= len;
			_str[_size] = '\0';
			return *this;
		}
		size_t Find(char ch, size_t pos = 0)//从第pos个位置往后找字符ch
		{
			assert(pos < _size);
			for (size_t i = pos; i < _size; ++i)
			{
				if (_str[i] == ch)
				{
					return i;
				}
			}
			return 0;
		}
		size_t Find(const char* str, size_t pos = 0)
		{
			assert(pos<_size);
			size_t begin = pos;//源字符串_str的下标从pos位置开始找
			size_t len = strlen(str);
			while (begin < _size)
			{
				size_t i = 0;//控制str的下标从0开始
				size_t start = begin;
				while (_str[start] == str[i])
				{
					++i;
					++start;
					if (i == len)//此时字符串str已经走到末尾了
					{
						return begin;
					}
				}
				++begin;
			}
			return -1;
		}


//capacity 容量操作
		void Resize(size_t newsize, char ch)//将有效字符的个数改成newsize个,多出的空间用字符ch填充
		{
			if (newsize > _size)
			{
				if (newsize > _capacity)
				{
					Reserve(newsize);
				}
				memset(_str + _size, ch, newsize - _size);//内存设置,将多出的空间置为ch
			}
			_size = newsize;
			_str[newsize] = '\0';
		}
		void Reserve(size_t newcapacity)//为字符串预留空间
		{
			//如果新的容量大于旧容量,增容
			if (newcapacity > _capacity)
			{
				char* str = new char[newcapacity + 1];
				strcpy(str, _str);
				//释放旧空间,使用新开辟的空间
				delete[] _str;
				_str = str;
				_capacity = newcapacity;
			}
		}
		void Clear()
		{
			_size = 0;
			_str[_size] = '\0';
		}
		size_t Size()const
		{
			return _size;
		}
		size_t Capacity()const
		{
			return _capacity;
		}
		bool Empty()const
		{
			return 0 == _size;
		}


//access下标访问
		char& operator[](size_t index)
		{
			assert(index < _size);
			return _str[index];
		}
		const char& operator[](size_t index)const
		{
			assert(index < _size);
			return _str[index];
		}
		//判断大小关系
		bool operator<(const String& s)const
		{
			size_t index1 = 0, index2 = 0;
			while (index1 < _size && index2 < s._size)
			{
				if (_str[index1] < s._str[index2])
				{
					return true;
				}
				++index1;
				++index2;
			}
			return false;
		}
		bool operator==(const String& s)const
		{
			//如果两个字符串的大小不等
			if (s._size != _size)
			{
				return false;
			}
			//大小相等,依次遍历两个字符串比较值是否相等
			size_t i = 0;
			while (_str[i] == s._str[i] && i < _size)
			{
				++i;
			}
			if (i == _size && s._str[i] == '\0')
			{
				return true;
			}
			return false;
		}
		bool operator>(const String& s)const
		{
			return !(*this < s || *this == s);
		}
		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);
		}

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


void TestString1()
{
	String s1("hello");
	String s2("world");
	String copy(s1);
	cout << s1.c_str() << endl;
	cout << s2.c_str() << endl;
	cout << copy.c_str() << endl;
	//利用迭代器打印String中 的元素
	String::iterator it = s1.begin();
	while (it != s1.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
	//范围for
	for (auto e : s1)
	{
		cout << e << " ";
	}
	cout << endl;
}
void TestString2()
{
	String s1("hello");
	s1.PushBack(' ');
	s1.PushBack('w');
	s1.PushBack('o');
	s1.PushBack('r');
	s1.PushBack('l');
	s1.PushBack('d');
	s1.PushBack(' ');
	s1.Append("code");
	cout << s1.c_str() << endl;
	s1 += 'A';
	cout << s1.c_str() << endl;
	s1 += "hehe";
	cout << s1.c_str() << endl;
	s1.Insert(2, 'a');
	cout << s1.c_str() << endl;
	s1.Insert(3, "copy");
	cout << s1.c_str() << endl;
	s1.Erase(3, 2);
	cout << s1.c_str() << endl;
	cout << s1.Find('c', 5) << endl;
	cout << s1.Find("py") << endl;

}
void TestString3()
{
	String s1("hello");
	s1.PushBack(' ');
	s1.PushBack('w');
	s1.PushBack('o');
	s1.PushBack('r');
	s1.PushBack('l');
	s1.PushBack('d');
	s1.PushBack(' ');
	s1.Append("code");
	cout << s1.Size() << endl;
	cout << s1.Capacity() << endl;
	s1.Clear();
	cout << s1.Size() << endl;
}
void TestString4()
{
	String s1("absehret");
	String s2("adgfiesk");
	cout << s1[2] << endl;
	cout << (s1 > s2) << endl;
	cout << (s1 < s2) << endl;
	cout << (s1 >= s2) << endl;
	cout << (s1 <= s2) << endl;
	cout << (s1 == s2) << endl;
	cout << (s1 != s2) << endl;
}

int main()
{
	TestString1();
	cout <<" "<< endl;
	TestString2();
	cout << " " << endl;
	TestString3();
	cout << " " << endl;
	TestString4();
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值