String2.0

#include <string.h>
#include <iostream>
#include <cassert>

using namespace std;

class String
{
private:
	enum { MULTIPLE = 8 };
	struct StrNode
	{
		size_t ref;      //引用计数
		size_t len;      //字符串的长度
		size_t cap;      //字符串的容量
		char data[];     //字符数组
	};
public:
	typedef char* iterator;
	typedef const char* const_iterator;

	iterator begin()
	{
		return (pstr != nullptr ? pstr->data : nullptr);
	}

	iterator end()
	{
		return (pstr != nullptr ? pstr->data + pstr->len : nullptr);
	}

	const_iterator begin()const
	{
		return (pstr != nullptr ? pstr->data : nullptr);
	}

	const_iterator end()const
	{
		return (pstr != nullptr ? pstr->data + pstr->len : nullptr);
	}


private:
	StrNode* pstr;

	static size_t Cal_Multiple_Of_Multipe(size_t n)
	{
		if (n == 0)
		{
			return MULTIPLE;
		}
		return (n % MULTIPLE == 0) ? n : (n / MULTIPLE + 1) * MULTIPLE;
	}

    //  return (n + ALIGN - 1) & ~(ALIGN - 1); //返会8的倍数

	static StrNode* My_Mollac(size_t n)
	{
		StrNode* newdata = (StrNode*)malloc(sizeof(StrNode) + sizeof(char) * n);
		memset(newdata, 0, sizeof(StrNode) + sizeof(char) * n);
		assert(newdata != nullptr);
		return newdata;
	}

	static StrNode* AddString(const char* pa, const char* pb, size_t n)
	{
		int total = String::Cal_Multiple_Of_Multipe(2 * n);
		StrNode* newdata = My_Mollac(total);
		newdata->ref = 1;
		newdata->cap = total - 1;
		newdata->len = n;
		strcpy_s(newdata->data, newdata->cap + 1, pa);
		strcat_s(newdata->data, newdata->cap + 1, pb);
		return newdata;
	}

	static StrNode* My_Realloc(StrNode* p, size_t n)
	{
		StrNode* newstr = (StrNode*)realloc(p, sizeof(StrNode) + sizeof(char) * n);
		assert(newstr != nullptr);
		return newstr;
	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值