C++----string类(模拟实现)

string类

#define _CRT_SECURE_NO_WARNINGS 
#include <iostream>
#include <assert.h>
using namespace std;
namespace zyf {
	class Mystring {
	public:
		typedef char* iterator;
		iterator begin() {
			return _str;
		}
		iterator end() {
			return _str + _size;
		}
		Mystring(const char* str = "")
			:_size(strlen(str)) {
			_capacity = _size;
			_str = new char[_capacity + 1];
			strcpy(_str, str);
		}
		~Mystring() {
			delete[] _str;
			_str = nullptr;
			_size = _capacity = 0;
		}
		//s1(s2)
		Mystring(const Mystring& s) {			
			_str = new char[s._size + 1];  //+1是给'\0'留位置
			strcpy(_str, s._str);
			_size = s._size;
			_capacity = s._size;
			/*_str = new char[s._capacity + 1];
			strcpy(_str, s._str);
			_size = s._size;
			_capacity = s._capacity;*/
		}
		//s1 = s2
		Mystring& operator=(const Mystring& s) {
			if (this != &s) {
				delete[] _str;
				_str = new char[s._size + 1];
				strcpy(_str, s._str);
				_size = s._size;
				_capacity = s._size;
			}
			return *this;
		}
		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];
		}
		void reserve(size_t n) {
			if (n > _capacity) {
				char* newstr = new char[n + 1];  
				strcpy(newstr, _str);
				delete[] _str;
				_str = newstr;
				_capacity = n;
			}
		}
		void resize(size_t n, char ch = '\0') {
			if (n < _size) {  //压缩空间,删除数据
				_size = n;
				_str[_size] = '\0';
			}
			else {  //插入数据					
				if (n > _capacity)  //空间不够先增容
					reserve(n);
				for (size_t i = _size; i < n; ++i)
					_str[i] = ch;
				_size = n;
				_str[_size] = '\0';  //初始化
			}
		}
		//s1.push_back('x');
		void push_back(char ch) {  //增容			
			if (_size == _capacity) {
				if (_capacity == 0)  //防止开始未预留空间
					reserve(2);
				else
					reserve(_capacity * 2);
			}
			_str[_size] = ch;
			++_size;
			_str[_size] = '\0';
		}
		//s1.append("xxxxxxxxxx");
		void append(const char* str) {  //尾插
			size_t len = strlen(str);
			if (_size + len > _capacity)
				reserve(_size + len);
			strcpy(_str + _size, str);  //直接拷贝到字符串尾
			_size += len;
		}
		//s1 += 'x'
		Mystring& operator+=(char ch) {
			this->push_back(ch);
			return *this;
		}
		//s1 += "xxxxx"
		Mystring& operator+=(const char* str) {
			this->append(str);
			return *this;
		}
		Mystring& insert(size_t pos, char ch) {  //字节
			assert(pos < _size);  //插入位置在范围内
			if (_size == _capacity)
				reserve(_capacity * 2);  //扩容两倍
			size_t end = _size;
			while (end >= pos) {
				_str[end + 1] = _str[end];
				--end;
			}
			_str[pos] = ch;
			++_size;
			return *this;
		}
		Mystring& insert(size_t pos, const char* str) {  //字符串
			assert(pos < _size);  //插入位置在范围内
			size_t len = strlen(str);
			if (_size + len > _capacity)
				reserve(_size + len);  //插入后字符串长度超过预留空间需要扩容
			size_t end = _size;
			while (end >= pos) {  //pos后字符串拷到新空间尾部
				_str[end + len] = _str[end];
				--end;
			}
			strncpy(_str + pos, str, len);  //在pos位置拷贝len个字节,不拷贝'\0'所以不用strcpy
			_size += len;
			return *this;
		}
		void erase(size_t pos, size_t len = npos) {
			assert(pos < _size);  //删除位置范围内
			if (_size - pos <= len) {  //节点位置+删除长度大于字符串长度,可直接从节点位置删除
				_str[pos] = '\0';
				_size = pos;
			}
			else {  //拷贝后面的字符串到删除位置,并更改字符串长度
				strcpy(_str + pos, _str + pos + len);
				_size -= len;
			}
		}
		size_t find(char ch, size_t pos = 0) {  //按值查找
			for (size_t 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 npos;
			else
				return p - _str;
		}
		//s1 < s2
		//实现<和=,复用实现其他比较
		bool operator<(const Mystring& s) {
			return strcmp(_str, s._str) < 0;
		}
		bool operator==(const Mystring& s) {
			return strcmp(_str, s._str) == 0;
		}
		bool operator<=(const Mystring& s) {
			return *this < s || *this == s;
		}
		bool operator>(const Mystring& s) {
			return !(*this <= s);
		}
		bool operator>=(const Mystring& s) {
			return !(*this < s);
		}
		bool operator!=(const Mystring& s) {
			return !(*this == s);
		}
	private:
		char* _str;
		size_t _size;
		size_t _capacity;
		static size_t npos;
	};
	size_t Mystring::npos = -1;  //整形最大数
	ostream& operator<<(ostream& out, const Mystring& s) {  //打印
		for (size_t i = 0; i < s.size(); ++i)
			out << s[i];
		return out;
	}
	istream& operator>>(istream& in, Mystring& s) {
		while (1) {  //输入
			char ch = in.get();
			if (ch == ' ' || ch == '\n')
				break;
			else
				s += ch;
		}
		return in;
	}
}
void test1() {
	zyf::Mystring s1("hello");
	s1.push_back('x');
	s1.push_back('y');
	s1.append("world");
	s1 += '!';
	s1 += "hello world";
	cout << s1 << endl;
	for (size_t i = 0; i < s1.size(); ++i) {	 //遍历+读写
		s1[i] += 1;
		cout << s1[i] << " ";
	}
	cout << endl;
	zyf::Mystring::iterator it1 = s1.begin();  //遍历+读写
	while (it1 != s1.end()) {
		*it1 -= 1;
		cout << *it1 << " ";
		++it1;
	}
	cout << endl;
	for (auto& ch : s1) {  //范围for是需要迭代器支持,被编译器自动转换成迭代器遍历
		ch += 1;
		cout << ch << " ";
	}
	cout << endl;
	zyf::Mystring s2("hello");
	s2 += 'x';
	s2.resize(3);
	s2.resize(7, 'x');
	s2.resize(15, 'x');
}
void test2() {
	zyf::Mystring s1("hello");
	s1.insert(2, 'e');
	cout << s1 << endl;
	s1.insert(2, "world");
	cout << s1 << endl;
	cout << s1.find("lde") << endl;
	zyf::Mystring s2("hello world wrold");
	cout << s2 << endl;
	s2.erase(5, 6);  //从第5个位置开始删6个字节
	cout << s2 << endl;
	s2.erase(5, 10);
	cout << s2 << endl;
}
int main() {
	test1();
	cout << endl;
	test2();
	return 0;
}

深浅拷贝

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <assert.h>
using namespace std;
namespace zyf {
	class Mystring {
	public:
		Mystring(const char*str = "")
			:_str(new char[strlen(str) + 1]) {
			strcpy(_str, str);
		}
		/*传统深拷贝写法
		string(const string&s)  
			:_str(new char[strlen(s._str) + 1]) {
			strcpy(_str, s._str);
		}
		string& operator=(const string&s) {
			if (this != &s) {
				delete[] _str;  //先释放空间,但不可以释放两次
				_str = new char[strlen(s._str) + 1];
				strcpy(_str, s._str);
			}
			return *this;
		}*/	
		Mystring(const Mystring& s)  //现代写法
			:_str(nullptr) {
			Mystring tmp(s._str);
			swap(_str, tmp._str);
		}	
		//若自己给自己赋值,仅交换空间
		Mystring& operator=(Mystring s) {  //利用swap实现的现代写法(更简洁)
			swap(_str, s._str);  //直接利用传参进行拷贝
			return *this;
		}
		/*Mystring& operator=(const Mystring &s) {  //第二种现代写法
			if (this != &s) {
				Mystring tmp(s._str);  //tmp出了作用域自动析构
				swap(_str, tmp._str);  //交换并释放不需要的自身空间
			}
			return *this;
		}*/
		~Mystring() {
			delete[] _str;
			_str = nullptr;
		}
		const char*c_str() {
			return _str;
		}
	private:
		char *_str;
	};
}
/*template<class T>  //交换变量自身
void swap(T&x1, T&x2) {  //x出作用域自动释放
	T x = x1;
	x1 = x2;
	x2 = x;
}*/
int main() {
	zyf::Mystring s1("hello");
	cout << s1.c_str() << endl;
	zyf::Mystring s2(s1);  //若自己不写拷贝函数,同一空间将会释放两次
	cout << s2.c_str() << endl;
	zyf::Mystring s3("world");
	s1 = s3;
	cout << s1.c_str() << endl;
	cout << s3.c_str() << endl;
	getchar();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值