C++系列-String(五)String初步的模拟实现

🌈个人主页: 羽晨同学

💫个人格言:“成为自己未来的主人~”   

今天,我们主要讲述的是如何实现String,首先,我们将在上一篇文章的初步实现String功能的前提上进一步对DString的功能进行完善。

这个头文件是我们这篇文章中将会实现的功能。

头文件声明

#pragma once
#include<iostream>
#include<assert.h>
using namespace std;
namespace bit
{
	class string
	{
	public:
		typedef char* iterator;
		typedef const char* const_iterator;
		iterator begin();
		iterator end();
		const_iterator begin() const;
		const_iterator end() const;

		string(const char* str = "");
		string(const string& s);
		~string();

		const char* c_str() const;
		size_t size() const;
		char& operator[](size_t pos);
		const char& operator[](size_t pos) 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 = 0, size_t len = npos);

		size_t find(char ch, size_t pos = 0);
		size_t find(const char* str, size_t pos = 0);

		void swap(string& s);
		string substr(size_t pos = 0, size_t len = npos);


		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;
		void clear();
	private:
		char* _str;
		size_t _size;
		size_t _capacity;
		const static size_t npos;

	};
	istream& operator>>(istream& is, string& str);
	ostream& operator<<(istream& os, const string& str);

}

这个头文件我们先放在这里,大家可以先看一下,具体的注意点我们在后面描述具体功能的时候进行讲解。

类域讲解和npos定义

 首先在String.cpp文件中,我们用到了类域的概念

#include"String.h"
namespace bit
{

}

我们将功能的具体实现的代码放到了与功能声明相同的类域当中,这样可以防止将具体的库展开从而造成混乱。

const size_t string::npos = -1;

首先,我们对npos进行了定义,将它定义为-1,除了在cpp文件中定义之外(我们一般都选择在类外进行定义),我们也可以在头文件当中对int类型的变量进行定义(只有Int类型)。

const static size_t npos = -1;

这样是可以的,但是这样是特例,我们一般来说不会这样做。

而且,同样都是声明中定义,其他类型就不行了,例如:

		const static double N = 2.2;

这样会进行报错。

接下来,我们对迭代器的开始和末尾进行的定义

	//迭代器的定义
	string::iterator string::begin()
	{
		return _str;
	}
	string::iterator string::end()
	{
		_str + _size;
	}
	string::const_iterator string::begin() const
	{
		return _str;
	}
	string::const_iterator string::end() const
	{
		return _str + _size;
	}

我们在这里为了防止权限的放大和缩小问题,所以我们还定义了const修饰的迭代器的开始和结束。

Sting构造

接下来,我们对string的构造(针对字符串)进行了定义。

针对字符串

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

 接下来,我们对string的构造(针对Sting类型变量)进行了定义。

针对String类型

	string::string(const string& s)
	{
		_str = new char[s._capacity + 1];
		strcpy(_str, s._str);
		_size = s._size;
		_capacity = s._capacity;
	}
void test_string1()
{
	string s1;
	string s2("hello world");
	string s3(s2);
	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
}

赋值拷贝 

	string& 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;
	}

析构

	string::~string()
	{
		delete[] _str;
		_str = nullptr;
		_size = _capacity = 0;
	}
	bit::string s4(s2);
	//cout << s4 << endl;
	bit::string s5 = s2;

返回整个Sting和它的size 

	const char* string::c_str() const
	{
		return _str;
	}
	
	size_t string::size() const
	{
		return _size;
	}

 方括号索引的搭建

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

 开辟空间函数(reserve)

	void string::reserve(size_t n)
	{
		if (n > _capacity)
		{
			char* tmp = new char[n + 1];
			strcpy(tmp, _str);
			delete[] _str;
			_str = tmp;
			_capacity = n;
		}
	}

 这个用条件判定的原因主要是为了节约资源,当空间足够用时自然没必要再对其进行开辟。

插入功能的实现

	void string::push_back(char ch)
	{
		if (_size == _capacity)
		{
			size_t newcapacity = _capacity == 0 ? 4 : 2 * _capacity;
			reserve(newcapacity);
		}
		_str[_size] = ch;
		_str[_size + 1] = '\0';
		++_size;
		//insert(_size, ch);
	}
	void string::append(const char* str)
	{
		size_t len = strlen(str);
		if (_size + len > _capacity)
		{
			reserve(_size + len);
		}
		strcpy(_str + _size, str);
		str += len;
		//insert(_size, str);
	}

这里实现的有两个函数,一个是push_back,一个是append

在二者的实现过程中,都对现有空间进行了判断,若空间不足,则使用reserve函数对空间进行开辟,并且释放旧的空间,并将现有的值放入新开辟的空间当中。

+=的实现

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

部分功能测试

void test_tring1()
{

	bit::string s1("hello world");
	cout << s1.c_str() << endl;
	for (size_t i = 0; i < s1.size(); i++)
	{
		s1[i]++;
	}
	for (size_t i = 0; i < s1.size(); i++)
	{
		cout << s1[i] << " ";
	}
	cout << endl;
	bit::string::iterator it1 = s1.begin();
	while (it1 != s1.end())
	{
		cout << *it1 << " ";
		++it1;
	}
	cout << endl;
	for (auto e : s1)
	{
		cout << e << " ";
	}
	cout << endl;
	const bit::string s3("xxxxxxxx");
	bit::string::const_iterator it3 = s3.begin();
	while (it3 != s3.end())
	{
		cout << *it3 << " ";
		it3++;
	}
	cout << endl;
	for (size_t i = 0; i < s3.size(); i++)
	{
		cout << s3[i] << " ";
	}
	cout << endl;
}

 

insert

	void string::insert(size_t pos, char ch)
	{
		assert(pos <= _size);
		if (_size == _capacity)
		{
			size_t newcapacity = _capacity == 0 ? 4 : 2 * _capacity;
			reserve(newcapacity);
		}
		int end = _size;
		while (end >= pos)
		{
			_str[end + 1] = _str[end];
			--end;
		}
		_str[pos] = ch;
		++_size;
	}

我们这个功能的实现逻辑基本上就是先将pos位置空下,空下的方式就是将前一位移动到后一位,然后将该位置插入需要的字符,然后将size+1

但是这个逻辑实现起来是有问题的。

	s1.insert(6, 'x');
	cout << s1.c_str() << endl;

当插入的目标位置为6的时候,是没问题的

 

但要是插入位置为0的时候,就会发生很大的问题

	s1.insert(0, 'y');
	cout << s1.c_str() << endl;

很明显,在这里的时候,发生了死循环,其实发生死循环的原因很简单,那就是size_t的存在,size_t是无符号整数,最小的数字就是0,所以,条件判定就失效了。

 所以,为了解决这个方法。我们一般会采用强制类型转换。

	while (end >= (int)pos)

 

或者,我们也可以转变代码逻辑

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

这样,就忽视了0的影响

	void string::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;
		}
		memcpy(_str + pos, str, len);
		_size += len;
	}

这个是针对字符串的。

或者同理修改代码逻辑

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

删除功能实现

	void string::erase(size_t pos, size_t len)
	{
		assert(pos < _size);
		if (len >= _size - pos)
		{
			_str[pos] = '\0';
			_size = pos;
		}
		else
		{
			strcpy(_str + pos, _str + pos + len);
			_size -= len;
		}

	}

在这个代码当中,我们并不需要一个个删除,我们只需要在删除的位置放一个‘\0’就好

查找功能实现

 查找字符

	size_t string::find(char ch, size_t pos)
	{
		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)
	{
		char* p = strstr(_str + pos, sub);
		return p - _str;
	}

Swap交换功能

void string::swap(string& s)
	{
		std::swap(_str, s._str);
		std::swap(_capacity, s._capacity);
		std::swap(_size, s._size);
	}

在这里我们为了提高效率,我们调用了库里面的swap函数,否则,我们必须要开辟三次空间,这样是很浪费的。

查找功能补充

string string::substr(size_t pos, size_t len)
	{
		if (len > _size - pos)
		{
			string sub(_str + pos);
			return sub;
		}
		else
		{
			string sub;
			sub.reserve(len);
			for (size_t i = 0; i < len; i++)
			{
				sub += _str[pos + i];
			}
			return sub;
		}
	 }

大小比较功能实现

	bool string::operator<(const string& s) const
	{
		return strcmp(_str, s._str) < 0;
	}
	bool string::operator>(const string& s) const
	{
		return !(*this <= s);

	}
	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 strcmp(_str, s._str) == 0;

	}
	bool string::operator!=(const string& s) const
	{
		return !(*this == s);
	}

补充功能:

 


	void string::clear()
	{
		_str[0] = '\0';
		_size = 0;
	}
	istream& operator>> (istream& is, string& str)
	{
		str.clear();
		char ch = is.get();
		while (ch != ' ' && ch != '\n')
		{
			str += ch;
			ch = is.get();
		}
		return is;
	}

	ostream& operator<<(ostream& os, const string& str)
	{
		for (size_t i = 0; i < str.size(); i++)
		{
			os << str[i];
		}
		return os;
	}

在输入功能的实现当中,我们选用的是get(),那是因为无论是scanf还是cin都不能识别换行符,其中scanf在%c的时候可以识别空格,但是其他时候也不可以。

好了,这篇文章的内容就到这里,我们下期再见。

  • 10
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值