String类的简单实现

文章目录

底层结构

基本结构,构造函数和析构函数

cpp 复制代码
namespace mystring
{
	class string
	{
	public:
		/*string()
		:_str(new char[1])
		, _size(0)
		, _capacity(0)
		{
		_str[0] = '\0';
		}

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

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

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


	private:
		char* _str;
		size_t _size;
		size_t _capacity;

public:
		static const int npos;
	};
	const int string::npos = -1;

	void StringTest1()
	{
		string s1("hello world");
	}
}

string类内

遍历

下标加[ ]

cpp 复制代码
        size_t size() const
		{
			return _size;
		}

		size_t capacity() const
		{
			return _capacity;
		}

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

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

迭代器(类似指针的版本)和范围for

cpp 复制代码
        typedef char* iterator;
		typedef const char* const_iterator;

		iterator begin() const
		{
			return _str;
		}

		iterator end() const
		{
			return _str + _size;
		}

至于为什么将迭代器实现之后范围for也直接实现了是因为:

范围for循环的背后机制会自动调用迭代器的begin()end()方法。这是C++标准库提供的一种语法糖,使得遍历容器变得非常方便。

当你定义了一个类,并希望使用范围for循环来遍历这个类的对象时,你需要在这个类中提供两种特殊的方法:

  1. begin()方法,返回指向容器中第一个元素的迭代器。
  2. end()方法,返回指向容器中最后一个元素之后的位置的迭代器。

这样,当你使用范围for循环时,编译器会自动调用这些方法来获取迭代器,然后遍历容器。

交换函数

cpp 复制代码
        //交换函数
		void swap(string& s)
		{
			std::swap(_str,s._str);
			std::swap(_size, s._size);
			std::swap(_capacity, s._capacity);
		}

         void swap(string& x, string& y)
	    {
		    x.swap(y);
	    }

深拷贝

cpp 复制代码
        //深拷贝
		/*string(const string& s)
		{
			_str = new char[s._capacity + 1];
			strcpy(_str,s._str);
			_size = s._size;
			_capacity = s._capacity;
		}*/
		
		//新写法
		string(const string& s)
		{
			string tmp(s._str);
			swap(tmp);
		}

		//s1=s3
		/*string& operator=(const string& s)
		{
			string ss(s);
			swap(ss);

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

			return *this;
		}

扩容函数

cpp 复制代码
        void reserve(size_t n)
		{
			if (n > _capacity)
			{
				char* tmp = new char[n+1];
				strcpy(tmp,_str);
				delete[] _str;
				_str = tmp;

				_capacity = n;
			}
		}

在pos前插入字符和字符串

cpp 复制代码
        //在pos前插入字符
		void insert(size_t pos, char ch)
		{
			assert(pos <= _size);

			if (_size == _capacity)
			{
				reserve(_capacity == 0 ? 4 : 2 * _capacity);
			}

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

		//在pos前插入字符串
		void insert(size_t pos, const char* str)
		{
			assert(pos <= _size);
			size_t len = strlen(str);//serlen计算str的长度
			if (_size + len > _capacity)
			{
				reserve(_size + len);
			}

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

			strncpy(_str + pos, str, len);
			_size += len;
			//_size++;
		}

在末尾追加一个字符和字符串

手搓版

cpp 复制代码
        //在末尾追加一个字符
		void push_back(char ch)
		{
			//二倍扩容
			if (_size == _capacity)
			{
				reserve(_capacity==0?4:2*_capacity);
			}

			_str[_size] = ch;
			++_size;
			_str[_size] = '\0';
		}

		//在末尾追加字符串
		void append(const char* str)
		{
			扩容
			size_t len = strlen(str);//serlen计算str的长度
			if (_size + len > _capacity)
			{
				reserve(_size + len);
			}

			strcpy(_str+_size,str);
			_size += len;
		}

精缩版

因为上面我们已经写了在pos前插入字符和字符串所以我们可以拿来直接用

cpp 复制代码
//在末尾追加一个字符
		void push_back(char ch)
		{
			insert(_size, ch);
		}

		//在末尾追加字符串
		void append(const char* str)
		{
			insert(_size, str);
		}

在pos前删除n个字符

cpp 复制代码
        //在pos位置删除n个字符
		void eraser(size_t pos,size_t len = npos)
		{
			assert(pos < _size);

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

operator+=接口

cpp 复制代码
		string& operator+=(char ch)
		{
			push_back(ch);
			return *this;
		}

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

find接口

cpp 复制代码
		//find
		size_t find(char ch, size_t pos = 0) const
		{
			for (size_t i = pos; i < _size; i++)
			{
				if (_str[i] == ch)
					return i;
			}
			return npos;
		}

		size_t find(char* str, size_t pos = 0) const
		{
			//kmp算法,字串匹配,bm算法了解一下
			assert(pos < _size);
			const char* p = strstr(_str + pos, str);
			if (p)
			{
				return p - _str;
			}
			else
			{
				return npos;
			}
		}

改变容器大小

cpp 复制代码
void resize(size_t n, char ch = '\0')
		{
			if (n <= _size)
			{
				_str[n] = '\0';
				_size = n;
			}
			else
			{
				reserve(n);
				for (size_t i = _size; i < n; i++)
				{
					_str[i] = ch;
				}
				_str[n] = '\0';
				_size = n;
			}
		}

取子串

cpp 复制代码
        //取子串
		string substr(size_t pos = 0, size_t len = npos)
		{
			string sub;
			if (len == npos || len >= _size - pos)
			{
				for (size_t i = pos; i < _size; i++)
				{
					sub += _str[i];
				}
			}
			else
			{
				for (size_t i = pos; i < pos + len; i++)
				{
					sub += _str[i];
				}
			}
			return sub;
		}

清除容器中的元素

cpp 复制代码
		void clear()
		{
			_size = 0;
			_str[_size] = '\0';
		}

string类外

operator重载

cpp 复制代码
bool operator==(const string& s1, const string& s2)
	{
		int ret = strcmp(s1.c_str(), s2.c_str());
		return ret == 0;
	}

	bool operator<(const string& s1, const string& s2)
	{
		int ret = strcmp(s1.c_str(), s2.c_str());
		return ret < 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);
	}

	bool operator!=(const string& s1, const string& s2)
	{
		return !(s1 == s2);
	}

流插入和流提取+输入流读取一行文本

cpp 复制代码
	ostream& operator<<(ostream& out, const string& s)
	{
		for (auto ch : s)
		{
			out << ch;
		}

		return out;
	}

	istream& operator>>(istream& in, string& s)
	{
		s.clear();
		char ch;
		//in >> ch;
		ch = in.get();
		while (ch != ' '&& ch != '\n')
		{
			s += ch;
			ch = in.get();
		}

		return in;
	}

	istream& getline(istream& in, string& s)
	{
		s.clear();
		char ch;
		//in >> ch;
		ch = in.get();
		char buff[128];
		size_t i = 0;
		while (ch != '\n')
		{
			buff[i++] = ch;
			if (i == 127)
			{
				buff[127] = '\0';
				s += buff;
				i = 0;
			}

			ch = in.get();
		}

		if (i > 0)
		{
			buff[i] = '\0';
			s += buff;
		}
		return in;
	}

完整版

.h

cpp 复制代码
#pragma once
#include <assert.h> 

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

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

		const char* c_str() const
		{
			return _str;
		}

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

		//深拷贝
		/*string(const string& s)
		{
			_str = new char[s._capacity + 1];
			strcpy(_str,s._str);
			_size = s._size;
			_capacity = s._capacity;
		}*/
		//新写法
		string(const string& s)
		{
			string tmp(s._str);
			swap(tmp);
		}

		//s1=s3
		/*string& operator=(const string& s)
		{
			string ss(s);
			swap(ss);

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

			return *this;
		}

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

		//扩容函数
		void reserve(size_t n)
		{
			if (n > _capacity)
			{
				char* tmp = new char[n+1];
				strcpy(tmp,_str);
				delete[] _str;
				_str = tmp;

				_capacity = n;
			}
		}

		//在末尾追加一个字符
		void push_back(char ch)
		{
			//二倍扩容
			/*if (_size == _capacity)
			{
				reserve(_capacity==0?4:2*_capacity);
			}

			_str[_size] = ch;
			++_size;
			_str[_size] = '\0';*/
			insert(_size, ch);
		}

		//在末尾追加字符串
		void append(const char* str)
		{
			//扩容
			//size_t len = strlen(str);//serlen计算str的长度
			//if (_size + len > _capacity)
			//{
			//	reserve(_size + len);
			//}

			//strcpy(_str+_size,str);
			//_size += len;
			insert(_size, str);
		}

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

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

		//在pos前插入字符
		void insert(size_t pos, char ch)
		{
			assert(pos <= _size);

			if (_size == _capacity)
			{
				reserve(_capacity == 0 ? 4 : 2 * _capacity);
			}

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

		//在pos前插入字符串
		void insert(size_t pos, const char* str)
		{
			assert(pos <= _size);
			size_t len = strlen(str);//serlen计算str的长度
			if (_size + len > _capacity)
			{
				reserve(_size + len);
			}

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

			strncpy(_str + pos, str, len);
			_size += len;
			//_size++;
		}

		//在pos位置删除n个字符
		void eraser(size_t pos,size_t len = npos)
		{
			assert(pos < _size);

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

		//交换函数
		void swap(string& s)
		{
			std::swap(_str,s._str);
			std::swap(_size, s._size);
			std::swap(_capacity, s._capacity);
		}

		//find
		size_t find(char ch,size_t pos = 0) const
		{
			for (size_t i = pos; i < _size; i++)
			{
				if (_str[i] == ch)
					return i;
			}
			return npos;
		}

		size_t find(char* str, size_t pos = 0) const
		{
			//kmp算法,字串匹配,bm算法了解一下
			assert(pos < _size);
			const char* p = strstr(_str + pos, str);
			if (p)
			{
				return p - _str;
			}
			else
			{
				return npos;
			}
		}

		//取子串
		string substr(size_t pos = 0, size_t len = npos)
		{
			string sub;
			if (len == npos || len >= _size - pos)
			{
				for (size_t i = pos; i < _size; i++)
				{
					sub += _str[i];
				}
			}
			else
			{
				for (size_t i = pos; i < pos + len; i++)
				{
					sub += _str[i];
				}
			}
			return sub;
		}

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

		//下标遍历
		size_t size() const
		{
			return _size;
		}

		size_t capacity() const
		{
			return _capacity;
		}

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

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

		//迭代器(范围for)遍历
		typedef char* iterator;
		typedef const char* const_iterator;

		iterator begin() const
		{
			return _str;
		}

		iterator end() const
		{
			return _str + _size;
		}

		void clear()
		{
			_size = 0;
			_str[_size] = '\0';
		}

	private:
		char* _str;
		size_t _size;
		size_t _capacity;

	public:
		static const int npos;
	};

	const int string::npos = -1;

	void swap(string& x, string& y)
	{
		x.swap(y);
	}

	bool operator==(const string& s1, const string& s2)
	{
		int ret = strcmp(s1.c_str(), s2.c_str());
		return ret == 0;
	}

	bool operator<(const string& s1, const string& s2)
	{
		int ret = strcmp(s1.c_str(), s2.c_str());
		return ret < 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);
	}

	bool operator!=(const string& s1, const string& s2)
	{
		return !(s1 == s2);
	}

	ostream& operator<<(ostream& out, const string& s)
	{
		for (auto ch : s)
		{
			out << ch;
		}

		return out;
	}

	istream& operator>>(istream& in, string& s)
	{
		s.clear();
		char ch;
		//in >> ch;
		ch = in.get();
		while (ch != ' '&& ch != '\n')
		{
			s += ch;
			ch = in.get();
		}

		return in;
	}

	istream& getline(istream& in, string& s)
	{
		s.clear();
		char ch;
		//in >> ch;
		ch = in.get();
		char buff[128];
		size_t i = 0;
		while (ch != '\n')
		{
			buff[i++] = ch;
			if (i == 127)
			{
				buff[127] = '\0';
				s += buff;
				i = 0;
			}

			ch = in.get();
		}

		if (i > 0)
		{
			buff[i] = '\0';
			s += buff;
		}
		return in;
	}

	void StringTest1()
	{
		string s1("hello world");
		string s2;

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

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

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

		const string s3("xxxxxxx");
		for (size_t i = 0; i < s3.size(); i++)
		{
			cout << s3[i] << " ";
		}
		cout << endl;
    }

	void StringTest2()
	{
		string s3("hello world");
		string::iterator it3 = s3.begin();
		while (it3 != s3.end())
		{
			cout << *it3 << " ";
			++it3;
		}
		cout << endl;

		const string s4("xxxxxxxx");
		string::const_iterator it4 = s4.begin();
		while (it4 != s4.end())
		{
			cout << *it4 << " ";
			++it4;
		}
		cout << endl;

		for (auto ch : s3)
		{
			cout << ch << " ";
		}
	}

	void StringTest3()
	{
		string s1("hello world!");
		cout << s1.c_str() << endl;
		s1 += 'x';
		cout << s1.c_str() << endl;
		s1 += "abcdefg";
		cout << s1.c_str() << endl;

		string s2("hello world");
		s2.insert(0, 'x');
		cout << s2.c_str() << endl;
	}

	void StringTest4()
	{
		string s1("hello world");
		cout << s1.c_str() << endl;
		/*s1.eraser(6, 3);
		cout << s1.c_str() << endl;*/

		string s2(s1);
		cout << s2.c_str() << endl;
		s2.resize(20, '*');
		cout << s2.c_str() << endl;

	}

	void StringTest5()
	{
		string s1("hello world");
		string s2("test");
		cout << s1.c_str() << endl;
		s1.insert(6,"xxx");
		cout << s1.c_str() << endl;
		cout << s2.c_str() << endl;
		s1.swap(s2);
		cout << s1.c_str() << endl;
		cout << s2.c_str() << endl;
	}

	void StringTest6()
	{
		string url("https://www.baidu.com/");

		size_t goal = url.find("baidu");
		cout << goal << endl;
	}

	void StringTest7()
	{
		string s1("asdfghjk");
		string s2("asdfghjk");

		cout << (s1 == s2) << endl;
		cout << (s1 == "asdfghjk") << endl;
		cout << ("asdfghjk" == s2) << endl;

		cout << s1 << endl;
		cout << s2 << endl;

		cin >> s1 >> s2;

		cout << s1 << endl;
		cout << s2 << endl;

		getline(cin,s1);

		cout << s1 << endl;
		cout << s2 << endl;
	}

	void StringTest8()
	{
		string s1("hello world");
		string s2;
		cout << s1 << endl;
		cout << s2 << endl;
		s2 = s1;
		cout << s1 << endl;
		cout << s2 << endl;
	}
}
相关推荐
小叶学C++5 分钟前
【C++】类与对象(下)
java·开发语言·c++
Funny_AI_LAB15 分钟前
MetaAI最新开源Llama3.2亮点及使用指南
算法·计算机视觉·语言模型·llama·facebook
NuyoahC22 分钟前
算法笔记(十一)——优先级队列(堆)
c++·笔记·算法·优先级队列
jk_10125 分钟前
MATLAB中decomposition函数用法
开发语言·算法·matlab
penguin_bark1 小时前
69. x 的平方根
算法
FL16238631291 小时前
[C++]使用纯opencv部署yolov11-pose姿态估计onnx模型
c++·opencv·yolo
sukalot1 小时前
windows C++-使用任务和 XML HTTP 请求进行连接(一)
c++·windows
这可就有点麻烦了1 小时前
强化学习笔记之【TD3算法】
linux·笔记·算法·机器学习
苏宸啊1 小时前
顺序表及其代码实现
数据结构·算法
lin zaixi()1 小时前
贪心思想之——最大子段和问题
数据结构·算法