学习->C++篇七:string类---下篇

string类的模拟实现 -> 实现一个简易的string类

目录

string类的模拟实现 -> 实现一个简易的string类

核心接口和成员变量:

具体实现:

简易测试:


核心接口和成员变量:

//在string.h文件中
#pragma once
#include<iostream>

using std::istream;
using std::ostream;

namespace myspace
{
	class string {
    public:
		//迭代器是原生指针
		typedef char* iterator;
		typedef char* const_iterator;
		iterator begin();
		iterator end();
		const_iterator begin()const;
		const_iterator end()const;
		//构造函数
		string(const string& s);
		string(const char* str="");
		//析构函数
		~string();
		//赋值重载
		string& operator=(const string&s);
		//[]重载
		char& operator[](size_t pos);
		const char& operator[](size_t pos)const;
		//+=重载
		string& operator+=(const char* str);
		string& operator+=(const string& s);
        string& operator+=(char ch);
		//返回c格式字符串
		const char* c_str() const;
		//容量相关函数
		size_t size();
		size_t capacity();
		void reserve(size_t n);
		void resize(size_t n, char ch = '\0');
		//增删查
		void push_back(char c);
		void append(const char* str);
		string& insert(size_t pos, char ch);
		string& insert(size_t pos, const char* str);
		string& erase(size_t pos, size_t len = npos);
		size_t find(char ch, size_t pos = 0);
		size_t find(char* str, size_t pos = 0);
		void clear();
	private:
		char* _str;
		size_t _size;     // 有效字符个数
		size_t _capacity; // 实际存储有效字符的空间
		const static size_t npos;
	};
	const size_t string::npos = -1;
	//非成员函数
	ostream& operator<<(ostream& out, const string& s);
	istream& operator>>(istream& in, const string& s);
	bool operator==(const string& s1, const string& s2);
	bool operator!=(const string& s1, const string& s2);
	bool operator<(const string& s1, const string& s2);
	bool operator<=(const string& s1, const string& s2);
	bool operator>(const string& s1, const string& s2);
	bool operator>=(const string& s1, const string& s2);
}

具体实现:

#pragma once
#include<iostream>
#include<assert.h>
#include<string.h>

using std::istream;
using std::ostream;

namespace myspace
{
	class string {
	public:
		//迭代器是原生指针
		typedef char* iterator;
		typedef 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(strlen(str))
		{
			_str = new char[_capacity + 1];
			strcpy(_str, str);
		}
		//传统写法
		/*string(const string& s)
			:_str(new char[s._capacity+1])
			,_size(s._size)
			,_capacity(s._capacity)
		{
			strcpy(_str, s._str);
		}*/
		//现代写法
		void swap(string& s)
		{
			std::swap(_str, s._str);
			std::swap(_size, s._size);
			std::swap(_capacity, s._capacity);
		}
		string(const string& s)
			:_str(nullptr)
			, _size(0)
			, _capacity(0)
		{
			string tmp(s._str);
			swap(tmp);
		}

		//析构函数
		~string()
		{
			if (_str)
			{
				delete[]_str;
				_str = nullptr;
				_size = _capacity = 0;
			}
		}

		//赋值重载
		//传统写法
		//string& operator=(const string& s)
		//{
		//	if (this != &s)
		//	{//先拷贝到tmp,避免开辟空间失败而_str数据丢失
		//		char* tmp = new char[s._capacity + 1];
		//		strcpy(tmp, s._str);
		//		delete[]_str;
		//		_str = tmp;
		//		_size = s._size;
		//		_capacity = s._capacity;
		//	}
		//	
		//	return *this;
		//}
		//现代写法
		string& operator=(string s)
		{
			swap(s);
			return *this;
		}

		//[]重载
		char& operator[](size_t pos) 
		{
			assert(pos < _size); 
			return _str[pos];
		}
		const char& operator[](size_t pos)const
		{ 
			assert(pos < _size); 
			return _str[pos];
		}

		//+=重载
		string& operator+= (const string& str) { append(str._str); return *this; }
		string& operator+=(const char* str) { append(str); return *this; }
		string& operator+=(char ch) { push_back(ch); return *this; }
		
		//返回c格式字符串
		const char* c_str() const { return _str; }
		
		//容量相关函数
		size_t size()const { return _size; }
		size_t capacity()const { return _capacity; }
		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 > _capacity)
				reserve(n);
			if (n > _size)
			{
				size_t index = _size;
				while (index < n)
					_str[index++] = ch;
			}
			_str[n] = '\0';
			_size = n;
		}
		
		//增删查
		void push_back(char c)
		{
			/*if (_size == _capacity)
				reserve(_capacity == 0 ? 4 : _capacity * 2);
			_str[_size++] = c;
			_str[_size] = '\0';*/
			insert(_size,c);
		}
		void append(const char* str)
		{
			/*int newlen = strlen(str) + _size;
			if (newlen > _capacity)
				reserve(newlen + 1);
			strcpy(_str + _size, str);
			_size = newlen;*/
			insert(_size, str);
		}
		string& insert(size_t pos, char ch)
		{
			assert(pos <= _size);
			if (_size == _capacity)
				reserve(_capacity == 0 ? 4 : _capacity * 2);
			//挪动数据
			size_t i = _size + 1;
			while (i > pos)
				_str[i--] = _str[i - 1];
			//插入
			_str[pos] = ch;
			_size++;
			return *this;
		}
		string& insert(size_t pos, const char* str)
		{
			assert(pos <= _size);
			int len = strlen(str);
			if (len + _size > _capacity)
				reserve(len + _size);
			//挪动数据
			size_t i = len + _size;
			while (i > pos + len - 1)
				_str[i--] = _str[i - len];
			strncpy(_str + pos, str, len);
			_size += len;
			return *this;
		}
		string& 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 i = pos + len;
				while (i <= _size)
					_str[i - len] = _str[i++];
				_size -= len;
			}
			return *this;
		}
		size_t find(char ch, size_t pos = 0)
		{
			for (; pos < _size; pos++)
			{
				if (_str[pos] == ch)
					return pos;
			}
			return npos;
		}
		size_t find(const char* str, size_t pos = 0)
		{
			const char* p = strstr(str, str + pos);
			if (p)
				return p-_str;
			return npos;
		}
		void clear()
		{
			_str[0] = '\0';
			_size = 0;
		}
	private:
		char* _str;
		size_t _size;     // 有效字符个数
		size_t _capacity; // 实际存储有效字符的空间
		const static size_t npos;
	};
	const size_t string::npos = -1;
	//非成员函数
	ostream& operator<<(ostream& out, const string& s)
	{
		for (auto e : s)
			out << e;
		return out;
	}
	istream& operator>>(istream& in, string& s)
	{
		s.clear();
		char ch = in.get();
		char buff[128] = { '\0' };
		int i = 0;
		while (ch != ' ' && ch != '\n')
		{
			buff[i++] = ch;
			if (i == 127)
			{
				s += buff;
				memset(buff, '\0', 128);
				i = 0;
			}
			ch = in.get();
		}
		s += buff;
		return in;
	}
	//比较关系运算符,写出<和==即可,其他的复用代码
	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); }
	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); }
}

简易测试:


void testMyString()
{
	using namespace myspace;
	string s1("hello world");
	string s2(s1);
	std::cin >> s2;
	cout << s1 << endl << s2 << endl << endl;

	s1 += "hhh";
	s2.insert(3, "dd find hh");
	cout << s1 << endl << s2 << endl << endl;
	cout << (s1 < s2) << endl;

	s1.insert(s1.find('o'), "<insert>");
	s2.insert(s2.find("find"), "<insert>");
	cout << s1 << endl << s2 << endl << endl;

	s1.clear();
	s2.erase(3);
	cout << s1 << endl << s2 << endl << endl;

	s1 = "hello";
	s2.resize(20, '9');
	cout << s1 << endl << s2 << endl << endl;
}

输出:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值