C++:string的模拟实现

目录

一、string类的声明

 二、string类的四个重要默认成员函数

2.1构造函数

2.2拷贝构造函数 

 2.3赋值运算符重载

 2.4析构函数

2.5现代写法 

三、string类的容量操作接口

 四、string类的修改操作接口

4.1在字符串末尾追加内容的接口

4.2插入字符的重载函数

4.3查找字符的接口 

4.4删除字符的接口 

五、string类的迭代器

六、string类中[]成员重载 

七 、string类中字符串比较运算符重载

八 、string类中流插入和流提取运算符重载

九、完整代码 

一、string类的声明

#define _CRT_SECURE_NO_WARNINGS 1

#pragma once
#include<assert.h>
#include<iostream>

using namespace std;

namespace bit

{

    class string

    {
    public:
        friend ostream& operator<<(ostream& cout, const string& s);
        friend istream& operator>>(istream& cin, string& s);

        typedef char* iterator;
        typedef const char* const_iterator;
    public:

        string(const char* str = "");

        string(const string& s);

        string& operator=(const string& s);

        ~string();

        // iterator

        iterator begin()
        {
            return _str;
        }
        iterator end()
        {
            return _str + _size;
        }
        const_iterator begin() const
        {
            return _str;
        }
        const_iterator end() const
        {
            return _str + _size;
        }
        // modify
        void push_back(char c);

        string& operator+=(char c);

        void append(const char* str);

        string& operator+=(const char* str);

        void clear();

        void swap(string& s);

        const char* c_str()const;
        // capacity

        size_t size()const;
        size_t capacity()const;
        bool empty()const;
        void resize(size_t newSize, char c = '\0');
        void reserve(size_t newCapacity);
        // access
        char& operator[](size_t index);
        const char& operator[](size_t index)const;
        //relational operators
        bool operator<(const string& s);

        bool operator<=(const string& s);

        bool operator>(const string& s);

        bool operator>=(const string& s);

        bool operator==(const string& s);

        bool operator!=(const string& s);
        // 返回c在string中第一次出现的位置
        size_t find(char c, size_t pos = 0) const;
        // 返回子串s在string中第一次出现的位置
        size_t find(const char* s, size_t pos = 0) const;
        // 在pos位置上插入字符c/字符串str,并返回该字符的位置
        string& insert(size_t pos, char c);
        string& insert(size_t pos, const char* str);
        // 删除pos位置上的元素,并返回该元素的下一个位置
        string& erase(size_t pos, size_t len);
    private:
        char* _str;
        size_t _capacity;
        size_t _size;
        const  static size_t npos = -1;
    };
}

 二、string类的四个重要默认成员函数

2.1构造函数
string::string(const char* str)
{
	_size = strlen(str);
	_capacity = _size;
	_str = new char[_capacity + 1];//这里加一是为了存储'\0'但是并不计入有效字符
	strcpy(_str, str);
}

 在类外声明需要注意类域和命名空间!因为在声明中已经给过了缺省参数(const char* str="")(常量字符串默认有'\0'结束)它确保类可以调用无参构造。同时缺省值只能在类的定义和声明中的一处给。

2.2拷贝构造函数 
string::string(const string& s)
{
	_str = new char[s._capacity + 1];
	strcpy(_str, s._str);
	_capacity = s._capacity;
	_size = s._size;
}
 2.3赋值运算符重载
string& string::operator=(const string& s)
{
	if (this != &s)
	{
		char* tmp = new char[s._capacity + 1];
		strcpy(tmp, s._str);
		delete[] _str;
		_str = tmp;
		_capacity = s._capacity;
		_size = s._size;
	}
	return *this;
}
 2.4析构函数
string::~string()
{
	delete[] _str;
	_str = nullptr;
	_capacity = 0;
	_size = 0;
}
2.5现代写法 
void string::swap(string& s)
{
    std::swap(_str,s._str);
    std::swap(_size,s._size);
    std::swap(_capacity,s._capacity);
}
string::string(const char* str)
{
	_size = strlen(str);
	_capacity = _size;
	_str = new char[_capacity + 1];
	strcpy(_str, str);
}
string::string(const string& s)
    :_str(nullptr)
{
    string tmp(s._str);//构造
    swap(tmp);
}
string& string::operator=(string s)//传值调用拷贝构造
{
    swap(s);
    return *this;  
}

三、string类的容量操作接口

size_t string::size()const
{
     return _size;
}
size_t string::capacity()const
{
     return _capacity;
}
bool string::empty()const
{
     return _size == 0;
}
void string::resize(size_t newSize, char c = '\0')
{
    if (newSize > _size)
     {
         // 如果newSize大于底层空间大小,则需要重新开辟空间
         if (newSize > _capacity)
         {
             reserve(newSize);
         }
            memset(_str + _size, c, newSize - _size);
     }
         _size = newSize;
         _str[newSize] = '\0';
}
void string::reserve(size_t newCapacity)
{
     // 如果新容量大于旧容量,则开辟空间
     if (newCapacity > _capacity)
      {
          char* str = new char[newCapacity + 1];
          strcpy(str, _str);
          // 释放原来旧空间,然后使用新空间
          delete[] _str;
          _str = str;
           _capacity = newCapacity;
       }
}

 四、string类的修改操作接口

4.1在字符串末尾追加内容的接口
//尾插一个字符
void string::push_back(char ch)
{
	if (_size == _capacity)
	{
		size_t newCapacity = _capacity == 0 ? 4 : _capacity * 2;
		reserve(newCapacity);//调用扩容接口
	}
	_str[_size] = ch;
	_size++;
	_str[_size] = '\0';
}
//在末尾追加一个字符串
void string::append(const char* str)
{
	size_t len = strlen(str);
	if (_size + len > _capacity)
	{
		reserve(_size + len);//调用扩容接口
	}
	strcpy(_str + _size, str);
	_size += len;
}

之后通过复用实现+=在字符串末尾追加字符或字符串. 

string& string::operator+=(char ch)
{
	push_back(ch);//复用push_back
	return *this;
}
string& string::operator+=(const char* str)
{
	append(str);//复用append
	return *this;
}
4.2插入字符的重载函数
//在指定位置插入一个字符
string& string::insert(size_t pos, char c)
{
		assert(pos <= _size);
		if (_size == _capacity)
		{
			size_t newCapacity = _capacity == 0 ? 4 : _capacity * 2;
			reserve(newCapacity);
		}
		size_t end = _size + 1;
		while (end>pos)
		{
			_str[end] = _str[end - 1];
			--end;
		}
		_str[pos] = c;
		_size++;

		return *this;
}
//在指定位置插入一个字符串
string& 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)//pos为无符号整型,所以end会减到-1,而-1的补码全是1, 因此会陷入死循环                     
	{
		_str[end + len] = _str[end];
		--end;
	}
	strncpy(_str + pos, str, len);
	_size += len;
	return *this;
}
4.3查找字符的接口 
//从下标位置开始查找字符c出现的位置
size_t string::find(char c, size_t pos) const
	{
		for (size_t i = pos; i < _size; i++)
		{
			if (_str[i] == c)
			{
				return pos;
			}	
		}
		return npos;
	}
//从下标位置开始查找字符串s出现的位置
size_t string::find(const char* s, size_t pos) const
{
	const char* ptr = strstr(_str + pos, s);
	if (ptr == nullptr)
	{
		return npos;
	}
	else {
		return ptr - _str;
	}
}
4.4删除字符的接口 
//从pos位置开始删除长度为len个字符
string& string::erase(size_t pos, size_t len)
{
	assert(pos < _size);
	if (len == npos || pos + len >= _size)
	{
		_str[pos] = '\0';
		_size = pos;
	}
	else {
		strcpy(_str + pos, _str + pos + len);
		_size -= len;
	}
	return *this;
}

五、string类的迭代器

string::iterator string::begin()
{
	return _str;
}
string::iterator string::end()
{
	return _str+_size;
}
string::const_iterator string::begin() const
{
	return _str;
}
string::const_iterator string::end() const
{
	return _str+_size;
}

六、string类中[]成员重载 

//[]成员重载用于返回字符串中指定下标字符串的引用
char& string::operator[](size_t index)
{
	assert(index <= _size);
	return _str[index];
}
//const成员函数是供const对象调用的
const char& string::operator[](size_t index) const
{
	assert(index <= _size);
	return _str[index];
}

七 、string类中字符串比较运算符重载

bool string::operator<(const string& s)const
{
	int res = strcmp(_str, s._str);
	if (res < 0)
		return true;
	return false;
}

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

八 、string类中流插入和流提取运算符重载

ostream& operator<<(ostream& cout, const string& s)
	{
		for (auto ch : s)
		{
			cout << ch;
		}
		return cout;
	}
	istream& operator>>(istream& cin, string& s)
	{
		s.clear();
		char buff[128];
		char ch = cin.get(); 
		int i = 0;
		while (ch != ' ' && ch != '\n')
		{
			buff[i++] = ch;
			if (i == 127)
			{
				buff[i] = '\0';
				s += buff;
				i = 0;
			}
			ch = cin.get();
		}
		if (i > 0)
		{
			buff[i] = '\0';
			s += buff;
		}
		return cin;
	}

九、完整代码 

#include"string.h"
namespace bit {

	string::string(const char* str)
	{
		_size = strlen(str);
		_capacity = _size;
		_str = new char[_capacity + 1];
		strcpy(_str, str);
	}
	string::string(const char* str)
	{
		_size = strlen(str);
		_capacity = _size;
		_str = new char[_capacity + 1];
		strcpy(_str, str);
	}
	string::string(const string& s)
		:_str(nullptr)
	{
		string tmp(s._str);//构造
		swap(tmp);
	}
	string& string::operator=(string s)//传值调用拷贝构造
	{
		swap(s);
		return *this;
	}
	/*string::string(const string& s)
	{
		_str = new char[s._capacity + 1];
		strcpy(_str, s._str);
		_capacity = s._capacity;
		_size = s._size;
	}
	string& string::operator=(const string& s)
	{

		if (this != &s)
		{
			char* tmp = new char[s._capacity + 1];
			strcpy(tmp, s._str);
			delete[] _str;
			_str = tmp;
			_capacity = s._capacity;
			_size = s._size;
		}
		return *this;
	}*/
	string::~string()
	{
		delete[] _str;
		_str = nullptr;
		_capacity = 0;
		_size = 0;
	}
	string::iterator string::begin()
	{
		return _str;
	}
	string::iterator string::end()
	{
		return _str + _size;
	}
	string::const_iterator string::begin() const
	{
		return _str;
	}
	string::const_iterator string::end() const
	{
		return _str + _size;
	}
	void string::push_back(char ch)
	{
		if (_size == _capacity)
		{
			size_t newCapacity = _capacity == 0 ? 4 : _capacity * 2;
			reserve(newCapacity);
		}
		_str[_size] = ch;
		_size++;
		_str[_size] = '\0';
	}
	void string::append(const char* str)
	{
		size_t len = strlen(str);
		if (_size + len > _capacity)
		{
			reserve(_size + len);
		}
		strcpy(_str + _size, str);
		_size += len;
	}
	string& string::operator+=(char ch)
	{
		push_back(ch);
		return *this;
	}
	string& string::operator+=(const char* str)
	{
		append(str);
		return *this;
	}
	void string::clear()
	{
		_size = 0;
		_str[0] = '\0';
	}
	void string::swap(string& s)
	{
		std::swap(_str, s._str);
		std::swap(_size, s._size);
		std::swap(_capacity, s._capacity);
	}
	const char* string::c_str() const
	{
		return _str;
	}
	size_t string::size()const
	{
		return _size;
	}
	size_t string::capacity()const
	{
		return _capacity;
	}
	bool string::empty()const
	{
		return _size == 0;
	}
	void string::resize(size_t newSize, char c = '\0')
	{
		if (newSize > _size)
		{
			// 如果newSize大于底层空间大小,则需要重新开辟空间
			if (newSize > _capacity)
			{
				reserve(newSize);
			}
			memset(_str + _size, c, newSize - _size);
		}
		_size = newSize;
		_str[newSize] = '\0';
	}
	void string::reserve(size_t newCapacity)
	{
		// 如果新容量大于旧容量,则开辟空间
		if (newCapacity > _capacity)
		{
			char* str = new char[newCapacity + 1];
			strcpy(str, _str);
			// 释放原来旧空间,然后使用新空间
			delete[] _str;
			_str = str;
			_capacity = newCapacity;
		}
	}
	char& string::operator[](size_t index)
	{
		assert(index <= _size);
		return _str[index];
	}
	const char& string::operator[](size_t index) const
	{
		assert(index <= _size);
		return _str[index];
	}
	bool string::operator<(const string& s)const
	{
		int res = strcmp(_str, s._str);
		if (res < 0)
			return true;
		return false;
	}

	bool string::operator<=(const string& s)const
	{
		return !(*this > s);
	}
	bool string::operator>(const string& s)const
	{
		int res = strcmp(_str, s._str);
		if (res > 0)
			return true;
		return false;
	}
	bool string::operator>=(const string& s)const
	{
		return !(*this < s);
	}
	bool string::operator==(const string& s)const
	{
		int res = strcmp(_str, s._str);
		if (res == 0)
			return true;
		return false;
	}
	bool string::operator!=(const string& s)const
	{
		return !(*this == s);
	}
	ostream& string::operator<<(ostream& cout, const string& s)
	{
		for (auto ch : s)
		{
			cout << ch;
		}
		return cout;
	}
	istream& operator>>(istream& cin, string& s)
	{
		s.clear();
		char buff[128];
		char ch = cin.get();
		int i = 0;
		while (ch != ' ' && ch != '\n')
		{
			buff[i++] = ch;
			if (i == 127)
			{
				buff[i] = '\0';
				s += buff;
				i = 0;
			}
			ch = cin.get();
		}
		if (i > 0)
		{
			buff[i] = '\0';
			s += buff;
		}
		return cin;
	}
	size_t string::find(char c, size_t pos) const
	{
		for (size_t i = pos; i < _size; i++)
		{
			if (_str[i] == c)
			{
				return pos;
			}
		}
		return npos;
	}
	size_t string::find(const char* s, size_t pos) const
	{
		const char* ptr = strstr(_str + pos, s);
		if (ptr == nullptr)
		{
			return npos;
		}
		else {
			return ptr - _str;
		}
	}
	string& string::insert(size_t pos, char c)
	{
		assert(pos <= _size);
		if (_size == _capacity)
		{
			size_t newCapacity = _capacity == 0 ? 4 : _capacity * 2;
			reserve(newCapacity);
		}
		size_t end = _size + 1;
		while (end > pos)
		{
			_str[end] = _str[end - 1];
			--end;
		}
		_str[pos] = c;
		_size++;

		return *this;
	}
	string& 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;
		}
		strncpy(_str + pos, str, len);
		_size += len;
		return *this;
	}
	string& string::erase(size_t pos, size_t len)
	{
		assert(pos < _size);
		if (len == npos || pos + len >= _size)
		{
			_str[pos] = '\0';
			_size = pos;
		}
		else {
			strcpy(_str + pos, _str + pos + len);
			_size -= len;
		}
		return *this;
	}

}

 

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值