C++ string类的模拟(详细代码实现)

c++string类的模拟实现,对重要部分进行优化,及注释

#pragma once
#include
using namespace std;

namespace selfstring
{
	class string
	{
	public:
		//string(const char* str)//第一种定义方式
		//	:_size(strlen(str))
		//	,_capacity(_size)
		//	,_str(new char[_capacity+1])//这里初始化的顺序是根据定义时的顺序来的,不是根据定义列表
		//{strcpy(_str, str);}
		//string(const char* str)//带参的
		//	:_size(strlen(str))
		//{
		//	_capacity = _size;
		//	_str = new char[_capacity + 1];
			//strcpy(_str, str);
		//}
		//string()//无参的
		//	:_size(0)
		//	, _capacity(0)
		//	, _str (new char[1])
		//{
		//	_str[0] = '\0';
		//}
		string(const char* str = "")//全缺省的构造
		{
			_size = (strlen(str));
			_capacity = _size;
			_str = new char[_capacity + 1];
			//strcpy(_str, str);
			memcpy(_str, str, _size + 1);
		}


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

		const char* c_str()const//()加上const只希望能读
		{
			return _str;
		}

		//size()我们只需要读就像
		size_t size()//()加上const
		{
			return _size;
		}

		//[]我们需要可读可写,因此我们可以实现两个版本,系统会自动调用最匹配的函数
		char& operator[](size_t i)
		{
			assert(i < _capacity);
			return _str[i];
		}
		const char& operator[](size_t i)const
		{
			assert(i < _capacity);
			return _str[i];
		}


		typedef char* iterator;//迭代器实现
		typedef const 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;
		}
		void reserve(size_t n)//可以修改容量
		{
			if (n > _capacity)//这个函数也会提供给外部使用,需要判断,防止缩容
			{
				char* tmp = new char[n + 1];//+1是给\0
				//strcpy(tmp, _str);
				memcpy(tmp, _str, _size + 1);//防止\0无法拷贝
				delete[]_str;
				_str = tmp;
				_capacity = n;
			}
		}
		void resize(size_t n, char ch = '\0')
		{
			if (n < _size)
			{
				_size = n;
				_str[_size] = '\0';
			}
			else
			{
				reserve(n);
				for (size_t i = _size; i < n; i++)
				{
					_str[i] = ch;
				}
				_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';

		}
		void append(const char* str)
		{
			size_t len = strlen(str);
			if (_size + len > _capacity)
			{
				reserve(_size + len);
			}
			//strcpy(_str+_size, str);//这里会会将\0也拷贝过去
			memcpy(_str + _size, str, len + 1);//+1是memcpy会将\0也拷贝过去
			_size += len;
		}
		string& operator+=(char ch)
		{
			push_back(ch);
			return *this;
		}
		string& operator+=(const char* str)
		{
			append(str);
			return *this;
		}
		void intsert(size_t pos, size_t n, char str)//从pos位置开始插入n个str
		{
			assert(pos <= _size);
			if (_size + n > _capacity)
			{
				reserve(_size + n);
			}
			//挪动数据,千万别动动了会出问题
			int end = _size;
			while (end >= (int)pos)//当插入为0时因为size_t的类型没有负数无法插入为0时的情况
			{
				_str[end + n] = _str[end];
				end--;
			}
			//第二种方式
			//size_t end = _size;
			//while (end >= (int)pos&& end!=npos)//当插入为0时因为size_t的类型没有负数无法插入为0时的情况
			//{
			//	_str[end + n] = _str[end];
			//	end--;
			//}
			for (size_t i = 0; i < n; i++)
			{
				_str[pos + i] = str;
			}
			_size += n;

		}
		void intsert(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;
			while (end >= (int)pos && end != npos)//当插入为0时因为size_t的类型没有负数无法插入为0时的情况
			{
				_str[end + len] = _str[end];
				end--;
			}
			for (size_t i = 0; i < len; i++)
			{
				_str[pos + i] = str[i];
			}
			_size += len;
		}
		void erase(size_t pos, size_t len = npos)
		{
			assert(pos <= _size);
			if (pos + len >= _size || len == npos)//删完
			{
				_str[pos] = '\0';
				_size = pos;
				_str[_size] = '\0';
			}
			else
			{
				size_t end = pos + len;
				while (end <= _size)
				{
					_str[pos++] = _str[end++];
				}
				_size -= len;

			}

		}
		size_t find(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* ch, size_t pos = 0)
		{
			assert(pos < _size);
			const char* str = strstr(_str + pos, ch);//找到会范围位置,没找到返回空
			if (str)
			{
				return str - _str;
			}
			else
			{
				return npos;
			}

		}
		string substr(size_t pos = 0, size_t len = npos)
		{
			size_t n = len;
			if (len == npos || pos + len > _size)
			{
				n = _size - pos;
			}
			string tmp;
			tmp.reserve(n);
			for (size_t i = pos; i < pos + n; i++)
			{
				tmp += _str[i];
			}
			return tmp;//这里会返回tmp的浅拷贝,
		}
		string(const string& s)//拷贝构造
		{
			_str = new char[s._capacity + 1];
			//strcpy(_str, s._str);
			memcpy(_str, s._str, s._size + 1);//防止string里有‘\0’
			_size = s._size;
			_capacity = s._capacity;
		}
		void clear()
		{
			_str[0] = '\0';
			_size = 0;
		}
		bool operator < (const string& s)
		{
			size_t i1 = 0;
			size_t i2 = 0;
			while (i1 < _size && i2 < s._size)
			{
				if (_str[i1] < s._str[i2])
				{
					return true;
				}
				else if (_str[i1] > s._str[i2])
				{
					return false;
				}
				else
				{
					i1++;
					i2++;
				}
			}
			if (i1 == _size && i2 != s._size)
			{

				return true;

			}
			else
			{
				return false;
			}

			return  _size < s._size;

		}
		bool operator < (const string& s)const
		{

			int sout = memcmp(_str, s._str, _size < s._size ? _size : s._size);
			return sout == 0 ? _size < s._size : sout < 0;
		}
		bool operator==(const string& s) const
		{
			return _size == s._size
				&& memcmp(_str, s._str, _size) == 0;
		}

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

		bool operator!=(const string& s) const
		{
			return !(*this == s);
		}
		void swap(string& s)
		{
			std::swap(_str, s._str);
			std::swap(_size, s._size);
			std::swap(_capacity, s._capacity);

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

	private:
		int _size;
		int _capacity;
		char* _str;
		static size_t npos;
	};
	size_t string::npos = -1;
};

ostream& operator<<(ostream& out,const selfstring::string& s)//注意自己定义string要放在该域名空间或者指定
{
	for (auto ch: s)//不能直接打印字符传,因为遇到\0会停止
	{
		out << ch;
	}
	return out;
}
istream& operator>>(istream& in, selfstring::string& s)//注意自己定义string要放在该域名空间或者指定
{
	s.clear();
	char ch = in.get();
	//处理缓冲区前的空格或换行
	while (ch == ' '||ch=='\n')
	{
		ch = in.get();
	}
	//让输入的字符都进入达到后+=到string
	char buff[128];
	int i = 0;
	while (ch != ' ' && ch != '\n')
	{
		buff[i++] = ch;
		if (i == 127)
		{
			buff[i] = '\0';
			s += buff;
			i = 0;
		}
		ch = in.get();
	}
	if (i != 0)
	{
		buff[i] = '\0';
		s += buff;
	}

	return in;
}

部分测试代码:

#include
using namespace std;
#include"string.h"
void testselfstring1()
{
	selfstring::string s1("hello world");
	cout << s1.c_str() << endl;
    
	selfstring::string s2;
	cout << s2.c_str() << endl;



	selfstring::string s3("hello world");
	cout << s3.c_str() << endl;

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

	const selfstring::string s4("hello world");
	//s4[2]++;//常量时编译器调用const的[]

	const selfstring::string s5("hello world");
	selfstring::string::const_iterator it = s5.begin();
	while (it != s5.end())
	{
		cout << *it << " ";
		it++;
	}
	cout << endl;

	for (auto ch : s5)
	{
		cout << ch << " ";

	}


}

void testselfstring2()
{
	selfstring::string s1("hello world");
	cout << s1.c_str() << endl;
	s1.append("i come");
	cout << s1.c_str() << endl;
	s1.push_back('l');
	cout << s1.c_str() << endl;
	s1 += '5';
	s1 += '6';
	s1 += "yyyy";
	cout << s1.c_str() << endl;

	
}
void testselfstring3()
{

	selfstring::string s1("hello world");
	cout << s1.c_str() << endl;
	/*s1.intsert(5, 3,'n');
	s1.intsert(0, "bbb");*/
	s1.erase(1,4);
	/*size_t pos=s1.find('o',)
	cout << s1.c_str() << endl;*/

}
void test1()
{

	selfstring::string s("xiao baidakeai");
	cout << s.c_str() << endl;
	s.resize(6, 'p');
	cout << s.c_str() << endl;
	s.resize(10, 'p');
	cout << s<< endl;
	cout << s.c_str() << endl;//c_str遇到\0就会停止,因此为避免打印不完全需要换掉strcpy



}

int main()
{
	//testselfstring3();
	test1();
	return 0;
}

你可能感兴趣的:(C++从入门到放弃,知识专题,c++)