string类简单的底层实现,了解string底层以及string的补充知识

string类的简单实现

头文件

#define  _CRT_SECURE_NO_WARNINGS 1
#pragma once
#include<iostream>
#include<assert.h>
using namespace std;
namespace exprience
{
	class string {
	public:
		typedef char* iterator;
		iterator begin()
		{
			return _str;
		}
		iterator end()
		{
			return _str + _size;
		}
		bool empty()const
		{
			return 0 == _size;
		}
		char operator[](size_t x)
		{
			assert(x < _size);
			return _str[x];
		}

		void swap(string& s)
		{
			char* ch= _str;
			size_t a = _capacity;
			size_t b = _size;
			_str = s._str;
			_capacity = s._capacity;
			_size = s._size;
			s._str = ch;
			s._capacity = a;
			s._capacity = b;
		}
		void reserve(size_t n=4)
		{
			if (n > _capacity)
			{
				char* str=nullptr;
				str = new char[n + 1];
				strcpy(str, _str);
				delete _str;
				_str = str;
				_capacity = n ;
			}
		}
		void resize(size_t n,char ch)
		{
			if (n > _size)
			{
				while (n > _capacity)
				{
					push_back(ch);
				}
			}
			else
			{
				_str[n] = '\0';
				_size = n;
			}
		}
		string()
		{
			_str = new char('\0');
			_size = 0;
			_capacity = 0;
		}
		string(const char* s)
		{
			size_t len = strlen(s);
			_str = new char[len+1];
			_capacity = len;
			_size = len;
			strcpy(_str, s);
		}
		string(char ch)
		{
			_str = new char[2];
			_capacity = 1;
			_size = 1;
			_str[0] = ch; _str[1] = '\0';
		}
		string(const string& s)
			:_str(nullptr)
		{
			string strtemp(s._str);
			swap(strtemp);
		}
		~string()
		{
			delete[]_str;
			_size = 0;
			_capacity = 0;
		}
		size_t size()
		{
			return _size;
		}
		char * c_str()
		{
			return _str;
		}
		string& operator=(string s)
		{
			string tem(s.c_str());
			swap(s);
			return *this;
		}
		void clear()
		{
			_str[0] = '\0';
			_size = 0;
		}
		string& operator+=(string& s);
		string& operator+=(const char* s);
		string& operator+=(char ch);
		void append(char ch);
		void append(const char* s);
		void append(string s);

		void insert(size_t pos,char ch);
		void insert(size_t pos, const char* s);
		void erase(size_t pos, size_t n=npos);
		void push_back(char ch);
		void pop_back();

		size_t find(size_t pos,char ch);
		size_t find(size_t pos, const char* 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);
		bool operator!=(const string& s);
		
	private:
		char* _str=nullptr;
		size_t _size=0;
		size_t _capacity=0;
		const static size_t npos = -1;
	};
	ostream& operator<<(ostream& out, string& s);
	istream& operator>>(istream& in,  string& s);

.cpp文件

#include"string.h"
namespace exprience {
	
	bool string::operator<(const string& s)
	{
		return strcmp(_str, s._str)<0;
	}
	bool string::operator<=(const string& s)
	{
		return strcmp(_str, s._str) <=0;
	}
	bool string::operator>(const string& s)
	{
		return !(*this <= s);
	}
	bool string::operator>=(const string& s)
	{
		return !(*this > s);
	}
	bool string::operator==(const string& s)
	{
		return strcmp(_str, s._str)==0;
	}
	bool string::operator!=(const string& s)
	{
		return !(*this == s);
	}
	void string::append(string s)
	{
		size_t newcapacity = _size + s._size;
		if (newcapacity >=_capacity)
		{
			newcapacity > 2 * _capacity ? reserve(newcapacity) : reserve(2 * _capacity);
		}
		strcat(_str, s.c_str());
		_size += s.size();
	}
	void string::append(char ch)
	{
		if (1 + _size >= _capacity)
		{
			reserve(2 * _capacity);
		}
		_str[_size++] = ch; _str[_size] = '\0';
	}
	void string::append(const char* s)
	{
		string tem(s);
		append(tem);
	}
	string& string::operator+=(string& s)
	{
		append(s);
		return *this;
	}
	string& string::operator+=(const char* s)
	{
		append(s);
		return *this;
	}
	string& string::operator+=(char ch)
	{
		append(ch);
		return *this;
	}
	void string::insert(size_t pos, char ch)
	{
		if (_size == 0)
		{
			reserve(4);
		}
		assert(pos < _size);
		if (1 + _size >= _capacity)
		{
			reserve(2 * _capacity);
		}
		size_t end = _size+1;
		for (size_t i = end; i > pos; i--)
		{
			_str[i] = _str[i-1];
		}
		_str[pos] = ch;
		_size++;
	}
	void string::insert(size_t pos, const char* s)
	{
		if (_size == 0)
		{
			reserve(4);
		}
		assert(pos < _size);
		size_t newcapacity = _size+strlen(s);
		if (newcapacity >= _capacity)
		{
			newcapacity > 2 * _capacity ? reserve(newcapacity) : reserve(2 * _capacity);
		}
		size_t len = strlen(s);
		if (len == 0)
		{
			return;
		}
		//最终结束位置
		size_t end = _size+len;
		size_t epos = pos + len;
		//循环次数
		for (size_t i = end; i >= epos; i--)
		{
			_str[i] = _str[i-len];
		}
		size_t i = 0;
		while (s[i] != '\0')
		{
			_str[pos++] = s[i++];
		}
		_size += len;
	}
	size_t string::find(size_t pos,char ch)
	{
		char* str = _str;
		for (char* i = str+pos; *i != '\0'; ++i)
		{
			if (*i == ch)
			return i - str;
		}
		return npos;
	}
	size_t string::find(size_t pos, const char* s)
	{
		char* str = _str+pos;
		char* pfind = strstr(str, s);
		if (pfind == nullptr)
		{
			return npos;
		}
		return pfind - _str;
	}
	void string::erase(size_t pos, size_t n)
	{
		assert(pos<_size);
		assert(n != 0);
		size_t end = _size;
		size_t residue = end - pos;
		if (n>=residue)
		{
			_str[pos] = '\0';
			_size -= (residue);
		}
		else
		{
		    size_t initposition = pos + n;
			for (size_t i = initposition; i <= end; ++i)
			{
				_str[i - n] = _str[i];
			}
			_size -= n;
		}
	}
	void string::push_back(char ch)
	{
		if (_size == 0)
		{
			reserve(4);
		}
		if (_capacity <= _size + 1)
		{

			_capacity==0?reserve(4):reserve(2 * _capacity);
		}
		_str[_size++] = ch;
		_str[_size] = '\0';
	}
	void string::pop_back()
	{
		assert(_size > 0);
		_str[--_size] = '\0';
	}
	ostream& operator<<(ostream& out,  string& s)
	{
		out<< s.c_str() << endl;
		return out;
	}
	istream& operator>>(istream& in, string& s)
	{
		s.clear();
		const int N = 300;
		char buff[N];
		char ch;
		int i = 0;
		ch=in.get();
		while (ch != ' ' && ch != '\n')
		{
			buff[i++] = ch;
			if (i == N - 1)
			{
				buff[i] = '\0';
				s += buff;
				i = 0;
			}
			ch=in.get();
		}
		if (i >0)
		{
			buff[i] = '\0';
			s += buff;
		}
		return in;
	}
	

}

Test文件

#include"string.h"
//测试拷贝构造 赋值构造
void Test1()
{
	exprience::string s1("hahaha");
	exprience::string s2=s1;
	exprience::string s3(s2);
	cout << s3.c_str() << endl;
	cout << s1.c_str() << endl;
	cout << s2.c_str() << endl;
	exprience::string s4='a';
	cout << s4.c_str() << endl;
	s4 = s1;
	cout << s4.c_str() << endl;
}
//测试运算符
void Test2()
{
	exprience::string s1("hahaha");
	exprience::string s2("hello ");
	exprience::string s3("world");
	s2 += s3;
	cout << s2.c_str() << endl;
	s2 += 'a';
	cout << s2;
	s2 += " lalala!";
	cout << s2.c_str() << endl;

	cin >> s1;
	if (s1 > s2)
		cout << "s1>s2" << endl;
	else
		cout << "s1<=s2" << endl;
	cout << "范围for 验证迭代器";
	for (auto it : s1)
	{
		cout << it;
	}
	cout << endl;
	cout << "[]验证下标::";
	for (int i = 0; i < s1.size(); ++i)
	{
		cout << s1[i] << " ";
	}
}
//增删查改
void Test3()
{
	exprience::string s1;
	s1.push_back('a');
	cout << s1;
	s1.insert(0, "hahaha");
	cout << s1;
	s1.insert(0, 'a');
	cout << s1;
	s1.erase(2, 3);
	cout << s1;
	s1.pop_back();
	cout << s1;
	cout<<s1.find(0, 'a')<<endl;
	cout << s1.find(0, "hha");
}
int main()
{
	Test3();
}

注意事项

1.string类在底层中是个模版,使用时是会实例化的,本次模拟实现只能直接写实例化的简单string

2.在构造时,我们写的拷贝构造和赋值构造是现代写法,利用临时对象进行普通构造,再利用swap把值交换,函数结束时,临时对象会自动销毁,调用析构,但是一定注意的是,我们必须要在拷贝构造时,使被拷贝对象的值为nullptr,这样交换时,析构的就是空指针而不是野指针

3.注意,在插入时,应考虑初始化的状态,删除时考虑string是否已经是空了

4.这个string类的实现是本人自己写的,可能还有一些bug

接下来单独看现代写法:

class String
{
public:
String(const char* str = "")
{
if (nullptr == str)
{
assert(false);
return;
}
_str = new char[strlen(str) + 1];
strcpy(_str, str);
}
String(const String& s)
: _str(nullptr)
{
String strTmp(s._str);
swap(_str, strTmp._str);
}
String& operator=(String s)
{
swap(_str, s._str);
return *this;
}

再看看传统写法:

class String
{
public:
String(const char* str = "")
{
// 构造String类对象时,如果传递nullptr指针,可以认为程序非
if (nullptr == str)
{
assert(false);
return;
}
_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)
{
char* pStr = new char[strlen(s._str) + 1];
strcpy(pStr, s._str);
delete[] _str;
_str = pStr;
}
return *this;
}
~String()
{
if (_str)
{
delete[] _str;
_str = nullptr;
}
}
private:
char* _str;
};

现代写法的好处还不只是,代码量少,以后模拟实现其他的容器还能更加体现出来。

在面试时,还有更好的写法可以参考:

#include <utility>
#include <string.h>

class String
{
 public:
  String()
    : data_(new char[1])
  {
    *data_ = '\0';
  }

  String(const char* str)
    : data_(new char[strlen(str) + 1])
  {
    strcpy(data_, str);
  }

  String(const String& rhs)
    : data_(new char[rhs.size() + 1])
  {
    strcpy(data_, rhs.c_str());
  }
  /* Delegate constructor in C++11
  String(const String& rhs)
    : String(rhs.data_)
  {
  }
  */

  ~String()
  {
    delete[] data_;
  }

  /* Traditional:
  String& operator=(const String& rhs)
  {
    String tmp(rhs);
    swap(tmp);
    return *this;
  }
  */
  String& operator=(String rhs) // yes, pass-by-value
  {
    swap(rhs);
    return *this;
  }

  // C++ 11
  String(String&& rhs)
    : data_(rhs.data_)
  {
    rhs.data_ = nullptr;
  }

  String& operator=(String&& rhs)
  {
    swap(rhs);
    return *this;
  }

  // Accessors

  size_t size() const
  {
    return strlen(data_);
  }

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

  void swap(String& rhs)
  {
    std::swap(data_, rhs.data_);
  }

 private:
  char* data_;
};

这是最简单的string类的实现了。

编码了解扩展知识

编码

我们人类的文字又各种各样的符号来表示,那么计算机也一样,在内存和磁盘中它是只能记住两个符号1和0

我们的整数当然可以用01表示

比如:0000表示0  0001表示1,我们可以使用二进制来表示

但是我们怎么表示文字呢?也就是说老美是怎么表示自己英文,也就是字符

这时候编码就出来了:编码就是值与符号的映射关系

那么Ascll编码表出来了

 这样通过值一一映射对应就可以打出英文了。

方框里头对应的就是它的ascll值

这样才只是解决了美国人的编码问题,那么随着国际化,此时是需要有一个涵盖所有前沿国家的编码表

万国码(unicode)

 对于万国码而言,只要对其有一些了解即可:

万国码有三种表现方式:UTF-8 UTF-16 UTF-32

先来介绍UTF-8

UTF-8有4种格式:

从一个字节代表1个字符到四个字节代表1个字符,UTF-8它是变长编码

会尽量使用最小字节数来表示一个字符。

作为万国码是兼容Ascll的,只要首字节的首位为0,那么此时代表的就是ascll。

一般而言中文是只要两个字节即可。

UTF-8可能比较乱,主要是字符对应的字节不一样。

UTF-16:固定一个字符为两个字节,具体的编码方式比较复杂

UTF-32:固定一个字符为四个字节,目前运用最广泛

GBK

它是我国的编码,一般在使用windows时,支持的 

代码验证

这里验证了,中文一般使用两个字节,改变一下就会改变映射关系。

其他string类

我们知道,在正常的string中,一般是使用字符作为类型的,但是除了正常的string还有其他几种string

正常string一个字符一个字节

他这里是只是UTF-8的。 

u16string一个字符两个字节

u32string一个字符4个字节

这样,就简单的了解一些编码的知识。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值