C++实现简易的string容器

        本篇文章简易的实现了string容器,调用了一些字符串函数(strcpy、strcmp......)使得代码更加简洁。


一、string构造函数

class String
	{
	private:
		char* _str;
		size_t _size;
		size_t _capacity;
	public:
		const static size_t npos = -1;
		//构造函数
		String(const char* str = "")
		{
			_size = strlen(str);
			_capacity = _size;
			_str = new char[_capacity+1]; //开空间
			//拷贝到_str中
			strcpy(_str, str);
		}
		//拷贝构造(深拷贝)
		String(const String& str)
		{
			this->_str = new char[str._capacity + 1];
			strcpy(_str,str._str);
			_size = str._size;
			_capacity = str._capacity;
		}
		//析构函数
		~String()
		{
			delete[] _str;
			_str = nullptr;
			_size = 0;
			_capacity = 0;
		}

二、重载操作符(+=、[]、<<)

//重载operator[]
		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 char* str)
		{
			append(str);
			return *this;
		}
		String& operator+=(const char& ch)
		{
			push_back(ch);
			return *this;
		}
//重载<<
	ostream& operator<< (ostream& cout, String& s1)
	{
		for (auto ch : s1)
		{
			cout << ch;
		}
		return cout;
	}

三、接口函数(insert、erase、find、substr)

        size_t find(const char ch, size_t pos=0)
		{
			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 char* ptr = strstr(_str+pos,str);
			if (ptr == nullptr)
				return npos;
			else
				return ptr - _str;
		}
		void erase(size_t pos,size_t len=npos)
		{
			if ((len == npos) || pos + len >= _size)
			{
				_str[pos] = '\0';
				_size = pos;
			}
			else
			{
				strcpy(_str+pos,_str+pos+len);
				_size -= len;
			}
		}
		string substr(size_t pos = 0, size_t len = npos)
		{
			assert(pos < _size);
			size_t end = pos + len;
			if (len == npos || pos + len >= _size)
			{
				end = _size;
			}
			string str;
			str.reserve(end - pos);
			for (size_t i = pos; i < end; i++)
			{
				str+=_str[i];
			}
			return str;
		}

总结

简易实现了string的部分功能。

猜你喜欢

转载自blog.csdn.net/m0_74058637/article/details/134634175
今日推荐