string类及其模拟实现

本文详细介绍了C++标准库中的string类,包括其接口、功能和使用方式,如构造函数、容量操作、访问遍历、修改操作等。同时,提供了简易的string类模拟实现,涵盖内存管理、赋值、插入、删除、查找等关键功能。通过实例展示了如何使用自定义的string类进行字符串操作。
摘要由CSDN通过智能技术生成

string类

1、标准库中的string类

为什么存在string类?:C语言中,字符串是以’\0’结尾的一些字符的集合,str系列库函数与字符串是分离开的,底层需要用户自己维护,且容易发生越界。

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

    string() – 构造空string类对象,也就是空字符串
    string(const char* s)-- 用c-string来构造string类对象
    string(size_t n,char c)-- string类包含n个字符c
    string(cosnt string& s)-- 拷贝构造函数

  2. string类对象的容量操作
    size – 返回字符串有效字符长度
    length – 返回字符串有效字符长度
    capacity – 返回空间总大小
    empty – 检测字符串是否为空,返回值true/false
    clear – 清空有效字符
    reserve – 为字符串预留空间
    resize – 将有效字符的个数改成n,多出的而空间用字符c填充

  3. string类对象的访问及遍历操作
    operator[] – 访问pos位置字符,const string类对象调用
    begin+end – begin获取第一个字符迭代器,end获取最后一个字符下一个位置迭代器
    rbegin+rend – begin获取第一个字符迭代器,end获取最后一个字符下一个位置迭代器
    范围for

  4. string类对象的修改操作
    push_back – 字符串后尾插字符c
    append – 在字符串后追加一个字符串
    operator+= – 字符串后追加字符串str
    c_str – 返回c格式字符串
    find+npos – 从字符串pos位置开始往后找字符串c,返回该字符在字符串中的位置
    rfind – 从字符串pos位置开始往前找字符串c,返回该字符在字符串中的位置
    substr – 在str中从pos位置开始,截取n个字符,然后将其返回

  5. string类非成员函数
    operator>> – 输入运算符重载
    operator<< – 输出运算符重载
    getline – 获取一行字符串

2、模拟实现string类

2.1 简单string类实现
namespace mm
{
	class string
	{
	public:	
		/*string()
			:_str(new char[1])
		{
			_str[0] = '\0';
		}
		
		string(char* str)
			:_str(new char[strlen(str)+1])
		{
			strcpy(_str, str);
		}*/

		string(char* str = "")
			:_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(const string& s)
			:_str(nullptr)
		{
			string tmp(s._str);
			swap(_str, tmp._str);
		}

		//赋值
		/*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;
		}

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

		size_t size()
		{
			return strlen(_str);
		}

		char& operator[](size_t i)
		{
			return _str[i];
		}

		const char* c_str()
		{
			return _str;
		}

		~string()
		{
			delete[] _str;
			_str = nullptr;
		}
		
	private:
		char* _str;
	};
}
2.2 string类完整实现
namespace mm
{
	class string
	{
	public:
		typedef char* iterator;
		iterator begin()
		{
			return _str;
		}

		iterator end()
		{
			return _str + _size;
		}

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

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

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

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

		string(const string& s)
			:_str(nullptr)
			, _size(0)
			, _capacity(0)
		{
			string tmp(s._str);//构造函数
			swap(tmp);
		}

		string& operator=(string s)
		{
			swap(s);
			return *this;
		}

		~string()
		{
			delete[] _str;
			_str = nullptr;
			_size = _capacity = 0;
		}

		size_t size()
		{
			return _size;
		}

		size_t size() const
		{
			return _size;
		}

		size_t capacity()
		{
			return _capacity;
		}

		char& operator[](size_t i)
		{
			assert(i < _size);
			return _str[i];
		}

		const char& operator[](size_t i) const
		{
			assert(i < _size);
			return _str[i];
		}

		const char* c_str()
		{
			return _str;
		}

		//开空间
		void reserve(size_t n)
		{
			if (n>_capacity)
			{
				char* newstr = new char[n+1];
				strcpy(newstr, _str);
				delete[] _str;
				_str = newstr;
				_capacity = n;
			}
		}

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

		string& insert(size_t pos, char ch)
		{
			assert(pos <= _size);
			if (_size == _capacity)
			{
				size_t newcapacity = _capacity == 0 ? 2 : _capacity * 2;
				reserve(newcapacity);
			}
			int end = _size;
			while (end>=(int)pos)
			{
				_str[end + 1] = _str[end];
				--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);
			}
			int end = _size;
			while (end >= (int)pos)
			{
				_str[end + len] = _str[end];
				--end;
			}
			/*strcpy(_str + pos, str); 会把str的\0拷贝过去*/
			strncpy(_str + pos, str, len);
			_size += len;
			return *this;
		}

		void push_back(const char ch)
		{
			/*if (_size == _capacity)
			{
				size_t newcapacity = _size == 0 ? 2 : _capacity * 2;
				reserve(newcapacity);
			}
			_str[_size] = ch;
			_size++;
			_str[_size] = '\0';*/
			insert(_size, ch);
		}

		void append(const char* str)
		{
			/*size_t len = strlen(str);
			if (len + _size > _capacity)
			{
				reserve(len + _size);
			}
			strcpy(_str + _size, str);
			_size += len;*/
			insert(_size, str);
		}

		//s+='a'
		string& operator+=(const char ch)
		{
			push_back(ch);
			return *this;
		}

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

		void erase(size_t pos,size_t len=npos)
		{
			assert(pos < _size);
			if (pos+len >= _size)
			{
				_str[pos] = '\0';
				_size = pos;
			}
			else
			{
				size_t i = pos + len;
				while (i <= _size)
				{
					_str[i - len] = _str[i];
					i++;
				}
				_size -= len;
			}
		}

		size_t find(char ch, size_t pos = 0)
		{
			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)
		{
			char* p = strstr(_str, str);
			if (p == nullptr)
				return npos;
			else
				return p - _str;
		}

		//strcmp(str1,str2) str1<str2返回<0 str1==str2返回0 str1>str2返回>0
		bool operator<(const string& s)
		{
			int ret = strcmp(_str, s._str);
			return ret < 0;
		}

		bool operator==(const string& s)
		{
			int ret = strcmp(_str, s._str);
			return ret == 0;
		}
		
		bool operator<=(const string& s)
		{
			return *this < s || *this == s;
		}
		
		bool operator>(const string& s)
		{
			return !(*this <= s);
		}

		bool operator>=(const string& s)
		{
			return !(*this < s);
		}

		bool operator!=(const string& s)
		{
			return !(*this == s);
		}

	private:
		char* _str;
		size_t _size;
		size_t _capacity;
		static size_t npos;
	};
	size_t string::npos = -1;
	ostream& operator<<(ostream& out, const string& s)
	{
		for (size_t i = 0; i < s.size(); i++)
		{
			cout << s[i];
		}
		return out;
	}

	istream& operator>>(istream& in, string& s)
	{
		while (1)
		{
			char ch;
			//in >> ch;//库里的实现,遇到空格或者换行停止
			ch = in.get();
			if (ch == ' ' || ch == '\n')
				break;
			else
				s += ch;
		}
		return in;
	}


	void test_string1()
	{
		string s;
		string s1(s);
		string s2("hello");
		cout << s << endl;
		cout << s1 << endl;
		cout << s2 << endl;

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

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

		string::iterator it = s2.begin();
		while (it != s2.end())
		{
			*it += 1;
			cout << *it << " ";
			++it;
		}
		cout << endl;

		for (auto ch : s2)
		{
			cout << ch << " ";
		}
		cout << endl;
		s.push_back('a');
		s += 'b';
		s += "cde";
		for (auto ch : s)
		{
			cout << ch << " ";
		}
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值