C++ STL -->模拟实现string


在之前的文章中 C++ STL–>String类详解,介绍了一下STL中string类的基本使用 这篇文章将模拟实现string类的常用函数

string模拟实现

模拟实现的目的就是为了更好的使用STL

模拟实现string类函数接口

namespace ding
{
   
   
   class string
   {
   
   
   public:
        string(const char* str = "");
        string(const string& s);
        string& operator=(const string& s);
        ~string();
        //=======================================================
        // iterator
        typedef char* iterator;
        iterator begin();
        iterator end();
        //=======================================================
        // modify
        void push_back(char c);
        void append(const char* str);
        string& operator+=(char c);
        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 n, char c = '\0');
        void reserve(size_t n);
        //=======================================================
        // 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;     //记录字符串当前的有效长度
   };
   ostream& operator<<(ostream& _cout, const ding::string& s);
   stream& operator>>(istream& _cin, ding::string& s);
};

为了解决和标准库中string命名发生冲突,这里使用自己的命名空间解决

默认成员函数

构造函数

无参构造函数:构造空字符串 空字符串里面是有一个\0的 并不是什么都没有

string::string()
	:_str(new char [1])
	,_capacity(0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C++下等马

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值