【C++】string的模拟实现

1、模拟实现string.h

❗🥳部分代码图解:

#pragma once

namespace My_String
{
	class string
	{
	public:
		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;
		}

		//无参
		//string()
		//	: _str(new char[1]) //最少开一个存'\0'
		//	, _size(0)
		//	, _capacity(0)
		//{
		//	_str[0] = '\0';
		//}

		//带参
		string(const char* str = "") //空的字符串,默认后面有一个'\0'
			: _size(strlen(str))
			, _capacity(_size) //不算'\0'大小
		{
			_str = new char[_capacity + 1]; //多开一个空间存'\0'
			strcpy(_str, str); //'\0'也会被拷贝
		}

		//拷贝构造【传统写法】
		/*string(const string& s)
		{
			_str = new char[s._capacity + 1];
			strcpy(_str, s._str);
			_size = s._size;
			_capacity = s._capacity;
		}*/

		//赋值【传统写法】
		/*string& operator=(const string& s)
		{
			if (this != &s)
			{
				char* tmp = new char[s._capacity + 1];
				strcpy(tmp, s._str);
				delete[] _str;
				_str = tmp;
				_size = s._size;
				_capacity = s._capacity;
			}
			return *this;
		}*/

		void swap(string& s)
		{
			std::swap(_str, s._str); //调用库里的swap
			std::swap(_size, s._size);
			std::swap(_capacity, s._capacity);
		}

		//拷贝构造【现代写法】s2(s1)
		string(const string& s)
			:_str(nullptr)
			,_size(0)
			,_capacity(0)
		{
			string tmp(s._str); //普通构造一个tmp
			swap(tmp); //【this->swap(tmp);】隐含的this就是s2
		}

		//赋值【现代写法】s2 = s3
		string& operator=(const string& s)
		{
			if (this != &s)
			{
				string tmp(s._str);
				swap(tmp);
			}
			return *this;
		}

		//赋值【现代写法简化】
		/*string& operator=(string tmp)
		{
			swap(tmp);
			return *this;
		}*/

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

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

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

		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]; //留一个位置给'\0'
				strcpy(tmp, _str);
				delete[]_str;
				_str = tmp;
				_capacity = n;
			}
		}

		void resize(size_t n, char ch = '\0')
		{
			if (n <= _size)
			{
				_str[n] = '\0';
				_size = n;
			}
			else
			{
				reserve(n);
				while (_size < n)
				{
					_str[_size] = ch;
					++_size;
				}
				_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(len + _size);
			}
			strcpy(_str + _size, str);
			_size += len;
		}

		string& operator+=(char ch)
		{
			push_back(ch);
			return *this;
		}

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

		void insert(size_t pos, char ch)
		{
			assert(pos <= _size);
			if (_size == _capacity)
			{
				reserve(_capacity == 0 ? 4 : _capacity * 2);
			}

			int end = _size;
			while (end >= (int)pos)
			{
				_str[end + 1] = _str[end];
				--end;
			}

			/*size_t end = _size + 1;
			while (end > pos)
			{
				_str[end] = _str[end - 1];
				--end;
			}*/

			_str[pos] = ch;
			_size++;
		}

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

			//strncmp(_str + pos, str, len);

			for (int i = 0; i < len; i++)
			{
				_str[pos] = str[i];
				pos++;
			}
			_size += len;
		}

		void erase(size_t pos, size_t len = npos)
		{
			assert(pos < _size); //_str[_size]='\0',所以不能=_size
			
			/*int p = pos;
			for (int i = 0; i < len; i++)
			{
				_str[p] = '\0';
				p++;
			}

			while (_str[pos + len] != '\0')
			{
				_str[pos] = _str[pos + len];
				pos++;
			}
			_str[pos] = '\0';
			_size = pos;*/

			if (pos + len >= _size || len == npos)
			{
				_str[pos] = '\0';
				_size = pos;
			}
			else
			{
				while (_str[pos + len] <= _size)
				{
					_str[pos] = _str[pos + len];
					pos++;
				}
				_size -= len;
			}
		}

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

		string substr(size_t pos, size_t len = npos)
		{
			string s;
			size_t end = pos + len;
			if (len == npos || pos + len >= _size)
			{
				end = _size;
				len = _size - pos;
			}

			reserve(len);

			for (int i = pos; i < end; i++)
			{
				s += _str[i];
			}
			return s;
		}

		bool operator<(const string& s) const
		{
			return strcmp(_str, s._str) < 0;
		}

		bool operator==(const string& s) const
		{
			return strcmp(_str, s._str) == 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 clear()
		{
			_str[0] = '\0';
			_size = 0;
		}

		const static size_t npos;

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

	const size_t string::npos = -1;

	//流插入和流提取不一定非得写成友元,日期类写成友元是因为要访问私有成员
	ostream& operator<<(ostream& out, const string& s)
	{
		/*for (size_t i = 0; i < s.size(); i++)
		{
			out << s[i];
		}*/

		for (auto ch : s)
		{
			out << ch;
		}

		return out;
	}

	/*istream& operator>>(istream& in, string& s)
	{
		s.clear(); //清理已有数据

		char ch;
		//in >> ch; //in不可以取到空格和换行,get可以
		ch = in.get();
		while (ch != ' ' && ch != '\n')
		{
			s += ch;
			ch = in.get();
		}

		return in;
	}*/

	//流提取优化【避免不断扩容,减少扩容次数,减少多开空间的浪费】
	istream& operator>>(istream& in, string& s)
	{
		s.clear();

		char buff[129]; //辅助空间,局部变量,函数结束数组就销毁了
		size_t i = 0;

		char ch;
		ch = in.get();
		while (ch != ' ' && ch != '\n')
		{
			buff[i] = ch;
			i++;

			if (i == 128)
			{
				s += buff; //按buff大小开空间,不会多开
				i = 0;
			}

			ch = in.get();
		}

		if (i != 0)
		{
			buff[i] = '\0';
			s += buff; //按buff大小开空间,不会多开
		}

		return in;
	}

	//测试
	void Test1()
	{
		string s1("Hello World");
		cout << s1.c_str() << endl;

		string s2;
		cout << s2.c_str() << endl;

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

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

		for (auto& ch : s1)
		{
			ch++;
			cout << ch;
		}
	}

	void Test2()
	{
		string s1 = "Hello";
		s1.push_back(' ');
		s1.append("World");
		cout << s1.c_str() << endl;

		s1 += '-';
		s1 += "Hello";
		cout << s1.c_str() << endl;

		string s2;
		s2.push_back('X');
		cout << s2.c_str() << endl;
	}

	void Test3()
	{
		string s1("ABCE");
		s1.insert(0, '%');
		s1.insert(4, 'D');
		s1.insert(s1.size(), 'F');
		cout << s1.c_str() << endl;
	}

	void Test4()
	{
		string s1("ABCDE");
		string s2("abcde");
		cout << (s1 >= s2) << endl;
		cout << (s1 <= s2) << endl;

		string s3("xyz");
		cin >> s3;
		//std::cout << s3 << endl; //加std是调用库里的该功能
		cout << s3 << endl;
	}

	void Test5()
	{
		string s1("ABC");
		s1.insert(0, "%%");
		s1.insert(s1.size(), "def");

		string s2("abcdef");
		//s2.erase(1, 2);
		s2.erase(s2.size() - 1, 1);
		//s2.erase(2, 6);

		cout << s2 << endl;
		cout << s2.size() << endl;
	}

	void Test6()
	{
		string s1("hello world");
		cout << s1 << endl;

		s1.resize(5);
		cout << s1 << endl;

		s1.resize(20, 'x');
		cout << s1 << endl;
	}

	void Test7()
	{
		string s1("test.cpp.tar.zip");
		//size_t i = s1.find('.');
		//size_t i = s1.rfind('.');

		//string s2 = s1.substr(i);
		//cout << s2 << endl;

		//协议、域名、资源名
		string s3("https://legacy.cplusplus.com/reference/string/string/rfind/");
		//string s3("ftp://www.baidu.com/?tn=65081411_1_oem_dg");

		string sub1, sub2, sub3;
		size_t i1 = s3.find(':');
		if (i1 != string::npos)
			sub1 = s3.substr(0, i1);
		else
			cout << "没有找到i1" << endl;

		size_t i2 = s3.find('/', i1 + 3);
		if (i2 != string::npos)
			sub2 = s3.substr(i1 + 3, i2 - (i1 + 3));
		else
			cout << "没有找到i2" << endl;

		sub3 = s3.substr(i2 + 1);

		cout << sub1 << endl;
		cout << sub2 << endl;
		cout << sub3 << endl;
	}

	void Test8()
	{
		string s1("hello world");
		string s2 = s1; //拷贝构造
		cout << s2 << endl;

		string s3("xxxxxxxxxxxx");
		s1 = s3; //赋值
		cout << s1 << endl;
	}

	void Test9()
	{
		string s1("hello world");
		cin >> s1;
		cout << s1 << endl;
	}
}

2、Test.cpp

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <string>
#include <assert.h>
using namespace std;

#include "模拟实现string.h" //编译时.h文件在此处展开,编译器向上找头文件,库里的东西都在std域里,只能写在std后边

int main()
{
	//测试模拟实现
	//My_String::Test9();


	string s1;
	cout << s1.capacity() << endl;
	
	string s2("hello world");
	cout << s2.capacity() << endl;
	
	// 小于16,字符串存到buff数组里面
	// 大于等于16,存在_str指向的空间
		
	//_buff[16]
	//_str
	//_size
	//_capacity
	
	//sizeof(s1)和sizeof(s2)一样大,都是一个指针,一个_size,一个_capacity,(其实还有一个buff数组),不算存字符串所另开的空间
	cout << sizeof(s1) << endl;
	cout << sizeof(s2) << endl;


	//VS是深拷贝
	string s3("xxxxxxxxxxxxxxxxxxxxxxxxxxx");
	string s4(s3);
	cout << (void*)s3.c_str() << endl; //打印char*类型的地址,一般被识别成字符串,要强转才可以打印地址
	cout << (void*)s4.c_str() << endl;

	return 0;
}
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值