C++(初阶)(九)——string模拟实现

string实现

string.h

c 复制代码
#pragma once
#include<assert.h>
#include<iostream>
#include<string>

using namespace std;

namespace A
{
	class string
	{
	public:
		string(const char* str = "")
			: _size(strlen(str))
		{
			_capacity = _size;
			//实际包含'\0'
			_str = new char[_size + 1];
			//将原字符拷贝,'\0'也是
			memcpy(_str, str, _size + 1);
		}

		//打印
		const char* c_str() const
		{
			return _str;
		}

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

		//遍历
		size_t size() const;
		char& operator[](size_t i);
		const char& operator[](size_t i) const;

		//迭代器
		//普通
		typedef char* iterator;
		iterator begin();
		iterator end();
		//const,本身可修改,内容不可修改
		typedef const char* const_iterator;
		const_iterator begin() const;
		const_iterator end() const;

		void reserve(size_t n);
		void push_back(char ch);
		void append(const char* str);
		string& operator+=(char ch);
		string& operator+=(const char* str);

		void insert(size_t pos, char ch);
		void insert(size_t pos, const char* str);
		void erase(size_t pos, size_t len);

		size_t find(char ch, size_t pos = 0) const;
		size_t find(const char* sub, size_t pos = 0) const;
		string substr(size_t pos = 0, size_t len = npos) const;
		string(const string& s);
		void clear();

		void swap(string& s);

		bool operator==(const string& s) const;
		bool operator<(const string& s) const;
		bool operator<=(const string& s) const;
		bool operator>(const string& s) const;
		bool operator>=(const string& s) const;
		bool operator!=(const string& s) const;

	private:
		char* _str;
		size_t _size;
		size_t _capacity;
	public: 
		static const size_t npos;
	};
	std::ostream& operator<<(std::ostream& os, const string& s);
	std::istream& operator>>(std::istream& is, string& s);
}

string.c

c 复制代码
#define _CRT_SECURE_NO_WARNINGS

#include"string.h"

namespace A
{
	const size_t string::npos = -1;

	size_t string::size() const
	{
		return _size;
	}
	char& string::operator[](size_t i)
	{
		assert(i < _size);
		return _str[i];
	}
	const char& string::operator[](size_t i) const
	{
		assert(i < _size);
		return _str[i];
	}

	//迭代器
	//普通
	string::iterator string::begin()
	{
		return _str;
	}
	string::iterator string::end()
	{
		return _str + _size;
	}
	//const,本身可修改,内容不可修改
	string::const_iterator string::begin() const
	{
		return _str;
	}
	string::const_iterator string::end() const
	{
		return _str + _size;
	}


	void string::reserve(size_t n)
	{
		//此处只做扩容,不做缩容
		if (n > _capacity)
		{
			char* tmp = new char[n + 1];
			//为了防止字符串中间部分有'\0',所以不使用strcpy,因为strcpy拷贝到'\0'就结束
			memcpy(tmp, _str, _size + 1);
			delete[] _str;
			_str = tmp;
			_capacity = n;
		}
	}

	void string::push_back(char ch)
	{
		if (_size == _capacity)
		{
			reserve(_capacity == 0 ? 4 : 2 * _capacity);
		}
		_str[_size++] = ch;
	}
	void string::append(const char* str)
	{
		size_t len = strlen(str);
		if (len + _size > _capacity)
		{
			size_t newcapacity = len + _size > _capacity ? len + _size : 2 * _capacity;
			reserve(newcapacity);
		}
		//末尾的'\0'也要拷贝
		memcpy(_str + _size, str, len + 1);
		//原本_size包含'\0',无需+1
		_size += len;
	}
	string& string::operator+=(char ch)
	{
		push_back(ch);
		return *this;
	}
	string& string::operator+=(const char* str)
	{
		append(str);
		return *this;
	}


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

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

	void string::insert(size_t pos, const char* str)
	{
		size_t len = strlen(str);
		if (len + _size > _capacity)
		{
			size_t newcapacity = len + _size > _capacity ? len + _size : 2 * _capacity;
			reserve(newcapacity);
		}

		//先挪动,再插入
		size_t end = _size;
		while (end+len > pos+len-1)
		{
			_str[end + len] = _str[end];
			end--;
		}

		size_t i = 0;
		while (len--)
		{
			_str[pos++] = str[i++];
			++_size;
		}
	}

	void string::erase(size_t pos, size_t len)
	{
		if (len == npos || len > _size - pos)
		{
			_str[pos++] = '\0';
			--_size;
		}
		else
		{
			//将剩余字符拷贝到pos位置
			memmove(_str + pos, _str + pos + len, _size + 1 - pos - len);;
			_size -= len;
		}
	}

	size_t string::find(char ch, size_t pos) const
	{
		assert(pos < _size);

		for (size_t i = pos; i < _size; i++)
		{
			if (_str[i] == ch)
			{
				return i;
			}
		}
		return npos;
	}
	size_t string::find(const char* sub, size_t pos) const
	{
		assert(pos < _size);
			
		const char* p = strstr(_str, sub);
		if (p == nullptr)
		{
			return npos;
		}
		else
		{
			return p - _str;
		}
	
	}
	string string::substr(size_t pos, size_t len) const
	{
		if (len > _size - pos)
		{
			len = _size - pos;
		}
		string ret;
		ret.reserve(len);
		for (size_t i = 0; i < len; i++)
		{
			ret += _str[pos + i];
		}
		return ret;
	}

	string::string(const string& s)
	{
		_str = new char[s._capacity + 1];
		memcpy(_str, s._str, s._size + 1);
		_size = s._size;
		_capacity = s._capacity;
	}

	std::ostream& operator<<(std::ostream& os, const string& s)
	{
		for (size_t i = 0; i < s.size(); i++)
		{
			os << s[i];
		}
		return os;
	}
	void string::clear()
	{
		_str[0] = '\0';
		_size = 0;
	}
	std::istream& operator>>(std::istream& is, string& s)
	{
		//s.clear();
		//char ch;
		//ch = is.get();
		//while (ch != ' ' && ch != '\n')
		//{
		//	s += ch;
		//	ch = is.get();
		//}
		//return is;

		//优化
		s.clear();

		char buff[256];
		int i = 0;
		char ch = is.get();
		while (ch != ' ' && ch != '\n')
		{
			buff[i++] = ch;
			ch = is.get();
			if (i == 255)
			{
				buff[i] = '\0';
				s += buff;

				i = 0;
			}
		}

		if (i > 0)
		{
			buff[i] = '\0';
			s += buff;
		}
		return is;
	}
	void string::swap(string& s)
	{
		std::swap(_str, s._str);
		std::swap(_size, s._size);
		std::swap(_capacity, s._capacity);
	}

	bool string::operator==(const string& s) const
	{
		size_t len1 = _size;
		size_t len2 = s._size;

		size_t n1 = 0, n2 = 0;
		while (n1 < len1 && n2 < len2)
		{
			if (_str[n1] != s._str[n2])
			{
				return false;
			}
			else
			{
				++n1;
				++n2;
			}
		}
		return n1 == len1 && n2 == len2;
	}

	bool string::operator<(const string& s) const
	{
		size_t len1 = _size;
		size_t len2 = s._size;

		size_t n1 = 0, n2 = 0;
		while (n1 < len1 && n2 < len2)
		{
			if (_str[n1] > s._str[n2])
			{
				return false;
			}
			else if (_str[n1] < s._str[n2])
			{
				return true;
			}
			else
			{
				++n1;
				++n2;
			}
		}

		if (n1 == len1 && n2 < len2)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	bool string::operator<=(const string& s) const
	{
		return (*this == s && *this < s);
	}
	bool string::operator>(const string& s) const
	{
		return !(*this <= s);
	}
	bool string::operator>=(const string& s) const
	{
		return !(*this < s);
	}
	bool string::operator!=(const string& s) const
	{
		return !(*this == s);
	}
}

test.cpp

c 复制代码
#define _CRT_SECURE_NO_WARNINGS

#include"string.h"

namespace A
{
	void test1()
	{
		string s1;
		cout << s1.c_str() << endl;

		string s2("hello world");
		cout << s2.c_str() << endl;

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

		const string s4("ni hao");
		//被const修饰,不能修改
		//s4[0]++;
		for (size_t i = 0; i < s3.size(); i++)
		{
			cout << s4[i] << " ";
		}
		cout << endl;
	}
	void test2()
	{
		string s1("hello world");
		string::iterator it = s1.begin();
		while (it != s1.end())
		{
			cout << *it << " ";
			it++;
		}
		cout << endl;

		string s2("hello world");
		string::iterator it2 = s2.begin();
		while (it2 != s2.end())
		{
			(*it2)++;
			cout << *it2 << " ";
			it2++;
		}
		cout << endl;

		const string s3("hello world");
		string::const_iterator it3 = s3.begin();
		while (it3 < s3.end())
		{
			//本身不可修改
			//(*it3)++;
			cout << *it3 << " ";
			it3++;
		}
		cout << endl;

		//是迭代器就支持范围for
		//范围for:单纯的替换迭代器
		for (auto x : s3)
		{
			cout << x << ' ';
		}
	}
	void test3()
	{
		string s1;
		s1.push_back('a');
		s1.push_back('a');
		s1.push_back('a');
		s1.push_back('a');
		s1.push_back('a');

		for (auto x : s1)
		{
			cout << x << " ";
		}
		cout << endl;

		string s2;
		s2.append("bbbbb");
		s2.append("ccccc");
		for (auto x : s2)
		{
			cout << x << " ";
		}
		cout << endl;

		string s3;
		s3 += 'x';
		s3 += '\0';
		s3 += '\0';
		s3 += 'x';
		s3 += 'x';
		for (auto x : s3)
		{
			cout << x << " ";
		}
		cout << endl;

		string s4;
		s4 += "abcdef";
		for (auto x : s4)
		{
			cout << x << " ";
		}
		cout << endl;
	}
	void test4()
	{
		//string s1("hello world");
		//s1.insert(0, 'x');
		//for (auto x : s1)
		//{
		//	cout << x << ' ';
		//}
		//cout << endl;

		string s2("hello world");
		s2.insert(0,"abcd");
		for (auto x : s2)
		{
			cout << x << ' ';
		}
		cout << endl;

		//s2.erase(3, 4);
		//for (auto x : s2)
		//{
		//	cout << x << ' ';
		//}
		//cout << endl;
	}

	void test5()
	{
		string s1("hello world");
		
		cout << s1.find('o') << endl;
		cout << s1.find("wor") << endl;

		string ss1(s1);
		cout << ss1 << endl;

		string ur1("https://cplusplus.com/reference/string/string/?kw=string");

		size_t pos1 = ur1.find(':');
		if (pos1 != string::npos)
		{
			string sub1 = ur1.substr(0, pos1);
			cout << sub1 << endl;
		}

		size_t pos2 = ur1.find('/', pos1 + 3);
		if (pos1 != string::npos)
		{
			string sub2 = ur1.substr(pos1 + 3, pos2 - (pos1 + 3));
			cout << sub2 << endl;

			string sub3 = ur1.substr(pos2 + 1);
			cout << sub3 << endl;
		}

	}
	void test6()
	{
		//string s1;
		//cin >> s1;
		//cout << s1 << endl;

		string s2("hello");
		string s3("world");
		cout << s2 << endl;
		cout << s3 << endl;

		//算法库的交换函数,使用三次拷贝,代价高
		//swap(s2, s3);
		s2.swap(s3);

		cout << s2 << endl;
		cout << s3 << endl;
	}

	void test7()
	{
		// ==
		//string s1("hello world");
		//string s2("hello");
		//string s3("hello");
		//string s4(s2);

		//cout << (s1 == s2) << endl;
		//cout << (s1 == s3) << endl;
		//cout << (s2 == s3) << endl;

		// <
		string s1("hello");
		string s2("hello world");
		string s3("hello");
		string s4(s2);

		cout << (s1 < s2) << endl;
		cout << (s1 < s3) << endl;
		cout << (s2 < s3) << endl;
	}
}


int main()
{
	//A::test1();
	//A::test2();
	//A::test3();
	//A::test4();
	//A::test5();
	A::test6();
	//A::test7();

	return 0;
}
相关推荐
ElseWhereR20 分钟前
困于环中的机器人
c++·算法·leetcode
Abaaba+1 小时前
【编译、链接与构建详解】Makefile 与 CMakeLists 的作用
linux·开发语言·c++
GalaxyPokemon1 小时前
C/C++ 基础 - 回调函数
c语言·开发语言·c++
巨可爱熊1 小时前
C++基础算法(插入排序)
java·c++·算法
Aurora_wmroy2 小时前
算法竞赛备赛——【数据结构】并查集
数据结构·c++·算法·蓝桥杯
虾球xz2 小时前
游戏引擎学习第196天
c++·学习·游戏引擎
pystraf2 小时前
P8310 〈 TREEのOI 2022 Spring 〉Essential Operations Solution
数据结构·c++·算法·线段树·洛谷
17´2 小时前
Qt从入门到入土(十一) -数据库操作--MySQL
数据库·c++·qt·mysql·sqlite
·醉挽清风·3 小时前
学习笔记—数据结构—二叉树(链式)
c语言·数据结构·c++·笔记·学习·算法
老歌老听老掉牙3 小时前
C++之曲线拟合与离散点生成
c++·离散·曲线拟合