【CPP】STL容器模拟实现篇之string

文章目录

全版本string

cpp 复制代码
#pragma once
#include <iostream>
#include <cstring>
#include <assert.h>
#include <list>
using namespace std;
namespace king
{
    class string
    {
    public:
        const static size_t npos = -1; // const static 可在类内声明同时初始化

    private:
        char *_str;
        size_t _size;
        size_t _capacity;

    public:
        // 无参构造
        // string()
        //     : _str(new char[1]), _size(0), _capacity(0)
        // {
        //     _str[0] = '\0';
        // }

        // 有参不缺省构造
        // string(const char *str)
        // {
        //     // 处理空指针
        //     if (str == nullptr)
        //     {
        //         _size = 0;
        //         _capacity = 0;
        //         _str = new char[1];
        //     }
        //     // 处理非法结尾
        //     size_t max_len = 1024 * 1024;
        //     size_t len = strnlen(str, max_len);
        //     if (len == max_len)
        //     {
        //         _size = len;
        //         _capacity = len;
        //         _str = new char[len + 1];
        //         memcpy(_str, str, len);
        //         _str[len] = '\0';
        //     }
        //     // 正常
        //     _size = strlen(str);
        //     _capacity = _size;
        //     _str = new char[_capacity + 1];
        //     strcpy(_str, str);
        // }

        // 全缺省构造函数
        string(const char *str = "")
        {
            _size = strlen(str);
            _capacity = _size;
            _str = new char[_capacity + 1];

            strcpy(_str, str);
            /*strncpy
            _size = strlen(str);
            _capacity = _size;
            _str = new char[_capacity + 1];
            strncpy(_str, str, _size);
            _str[_size] = '\0';
            */
        }
        // string s1(s);
        string(const string &s)
            : _str(new char[s._capacity + 1]), _size(s._size), _capacity(s._capacity)
        {
            strcpy(_str, s._str);
        }

        // 拷贝构造
        void swap(string &t)
        {
            ::swap(_str, t._str);
            ::swap(_size, t._size);
            ::swap(_capacity, t._capacity);
        }
        // string s1(s);
        string(const string &s)
            : _str(nullptr), _size(0), _capacity(0)
        {
            string t(s._str);
            swap(t); // this->swap(t);
        }

        // 析构函数
        ~string()
        {
            delete[] _str;
            _str = nullptr;
            _size = _capacity = 0;
        }
        // string s1 = s;
        string &operator=(const string &s)
        {
            if (this != &s)
            {
                // 在析构_str之前 先创建一个临时变量执行new语句
                // 如果此时出错 程序中止 不会执行delete语句
                char *tmp = new char[s._capacity + 1];
                delete[] _str;
                strcpy(tmp, s._str);
                _str = tmp;
                _size = s._size;
                _capacity = s._capacity;
            }
            return *this;
        }
        string &operator=(const string &s)
        {
            if (this != &s)
            {
                string tmp(s);
                swap(tmp);
            }
            return *this;
        }
        string &operator=(string s)
        {
            swap(s);
            return *this;
        }
        // 移动构造函数
        string(string &&s) noexcept
            : _str(s._str), _size(s._size), _capacity(s._capacity)
        {
            s._str = nullptr;
        }

        // 移动赋值运算符
        string &operator=(string &&s) noexcept
        {
            delete[] _str;
            _str = s._str;
            _size = s._size;
            _capacity = s._capacity;
            s._str = nullptr;
            return *this;
        }
        // c_str
        const char *c_str() const
        {
            return _str;
        }
        // size()
        size_t size() const
        {
            return _size;
        }
        // capacity()
        size_t capacity() const
        {
            return _capacity;
        }

        // 下标访问
        char &operator[](size_t pos)
        {
            assert(pos < _size);

            return _str[pos];
        }
        // 下标访问 const
        const char &operator[](size_t pos) const
        {
            assert(pos < _size);

            return _str[pos];
        }

        // 迭代器
        typedef char *iterator;
        typedef const char *const_iterator;

        // 头
        iterator begin()
        {
            return _str;
        }
        // 尾
        iterator end()
        {
            return _str + _size;
        }
        // 头 const
        const_iterator begin() const
        {
            return _str;
        }
        // 尾 const
        const_iterator end() const
        {
            return _str + _size;
        }

        // insert插入字符函数
        string &insert(size_t pos, char ch)
        {
            assert(pos <= _size);

            // 满了就扩容
            if (_size == _capacity)
            {
                reserve(_capacity == 0 ? 4 : _capacity * 2);
            }

            size_t end = _size + 1;
            while (end > pos)
            {
                _str[end] = _str[end - 1];
                --end;
            }

            _str[pos] = ch;
            ++_size;

            return *this;
        }

        // insert插入字符串函数
        string &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 + len;
            while (end >= pos + len)
            {
                _str[end] = _str[end - len];
                --end;
            }
            // 拷贝内容
            strncpy(_str + pos, str, len);
            _size += len;

            return *this;
        }
        // 删除len个字符
        void erase(size_t pos, size_t len = npos)
        {
            assert(pos < _size);

            if (len == npos || pos + len >= _size)
            {
                _str[pos] = '\0';
                _size = pos;
            }
            else
            {
                strcpy(_str + pos, _str + pos + len);
                _size -= len;
            }
        }

        // 预留空间
        void reserve(size_t n)
        {
            if (n > _capacity)
            {
                char *tmp = new char[n + 1]; // 开新空间
                strcpy(tmp, _str);           // 拷贝内容
                delete[] _str;               // 释放原空间

                _str = tmp;    // 更新指针指向
                _capacity = n; // 拷贝容量
            }
        }

        // 预留空间 + 初始化
        void resize(size_t n, char ch = '\0')
        {
            if (n > _size)
            {
                // 插入数据
                reserve(n);
                for (size_t i = _size; i < n; ++i)
                {
                    _str[i] = ch;
                }
                _str[n] = '\0';
                _size = n;
            }
            else
            {
                // 删除数据
                _str[n] = '\0';
                _size = n;
            }
        }

        // 插入字符 push_back
        void push_back(char ch)
        {
            insert(_size, ch);
        }

        // 插入字符串 append
        void append(const char *str)
        {
            insert(_size, str);
        }

        void append(const string &s)
        {
            append(s._str);
        }
        void append(size_t n, char ch)
        {
            reserve(_size + n);
            for (size_t i = 0; i < n; ++i)
            {
                push_back(ch);
            }
        }

        // +=字符
        string &operator+=(char ch)
        {
            push_back(ch);
            return *this;
        }
        // +=字符串
        string &operator+=(const char *str)
        {
            append(str);
            return *this;
        }

        // 清空字符串
        void clear()
        {
            _str[0] = '\0';
            _size = 0;
        }

        // find函数查找字符
        size_t find(char ch, size_t pos = 0) const
        {
            assert(pos < _size);

            for (size_t i = pos; i < _size; ++i)
            {
                if (ch == _str[i])
                {
                    return i;
                }
            }

            return npos;
        }

        // find函数查找字符串
        size_t find(const char *sub, size_t pos = 0) const
        {
            assert(sub);
            assert(pos < _size);

            const char *ptr = strstr(_str + pos, sub);
            if (ptr == nullptr)
            {
                return npos;
            }
            else
            {
                return ptr - _str;
            }
        }

        // substr函数 从pos处取len个字符作为子串返回
        string substr(size_t pos, size_t len = npos) const
        {
            assert(pos < _size);
            size_t realLen = len;
            if (len == npos || pos + len > _size)
            {
                realLen = _size - pos;
            }

            string sub;
            for (size_t i = 0; i < realLen; ++i)
            {
                sub += _str[pos + i];
            }

            return sub;
        }

        // 比较大小
        bool operator>(const string &s) const
        {
            return strcmp(_str, s._str) > 0;
        }
        // 比较相等
        bool operator==(const string &s) const
        {
            return strcmp(_str, s._str) == 0;
        }
        // 判断 >=
        bool operator>=(const string &s) const
        {
            return *this > s || *this == s;
        }
        // 判断 <=
        bool operator<=(const string &s) const
        {
            return !(*this > s);
        }
        // 判断 <
        bool operator<(const string &s) const
        {
            return !(*this >= s);
        }
        // 判断 !=
        bool operator!=(const string &s) const
        {
            return !(*this == s);
        }
    };

    // size_t string::npos = -1;

    // 流插入
    // ostream &operator<<(ostream &out, string &s)
    // {
    //     out << s._ptr; // 需要声明为友元函数
    //     return out;
    // }
    ostream &operator<<(ostream &out, const string &s)
    {
        for (size_t i = 0; i < s.size(); ++i)
            out << s[i];
        return out;
    }
    // 流提取--类比缓冲区 优化代码
    istream &operator>>(istream &in, string &s)
    {
        s.clear();

        char ch;
        ch = in.get();

        const size_t N = 32;
        char buff[N];
        size_t i = 0;

        while (ch != ' ' && ch != '\n')
        {
            buff[i++] = ch;
            if (i == N - 1)
            {
                buff[i] = '\0';
                s += buff;
                i = 0;
            }

            ch = in.get();
        }

        buff[i] = '\0';
        s += buff;

        return in;
    }
}

精简版string

cpp 复制代码
#pragma once
#include <iostream>
#include <cstring>
#include <assert.h>
#include <list>
using namespace std;
namespace king
{
    class string
    {
    public:
        const static size_t npos = -1; // const static 可在类内声明同时初始化
        void swap(string &t)
        {
            ::swap(_str, t._str);
            ::swap(_size, t._size);
            ::swap(_capacity, t._capacity);
        }

    private:
        char *_str;
        size_t _size;
        size_t _capacity;

    public:
        // 全缺省构造函数
        string(const char *str = "")
        {
            _size = strlen(str);
            _capacity = _size;
            _str = new char[_capacity + 1];

            strcpy(_str, str);
        }
        // 析构函数
        ~string()
        {
            delete[] _str;
            _str = nullptr;
            _size = _capacity = 0;
        }

        // string s1(s);
        string(const string &s)
            : _str(nullptr), _size(0), _capacity(0)
        {
            string t(s._str);
            swap(t); // this->swap(t);
        }
        // 移动构造函数
        string(string &&s) noexcept
            : _str(s._str), _size(s._size), _capacity(s._capacity)
        {
            s._str = nullptr;
        }
        string &operator=(string s)
        {
            swap(s);
            return *this;
        }
        // 移动赋值运算符
        string &operator=(string &&s) noexcept
        {
            delete[] _str;
            _str = s._str;
            _size = s._size;
            _capacity = s._capacity;
            s._str = nullptr;
            return *this;
        }

        // c_str
        const char *c_str() const
        {
            return _str;
        }
        // size()
        size_t size() const
        {
            return _size;
        }
        // capacity()
        size_t capacity() const
        {
            return _capacity;
        }

        // 下标访问
        char &operator[](size_t pos)
        {
            assert(pos < _size);

            return _str[pos];
        }
        // 下标访问 const
        const char &operator[](size_t pos) const
        {
            assert(pos < _size);

            return _str[pos];
        }

        // 迭代器
        typedef char *iterator;
        typedef const char *const_iterator;

        // 头
        iterator begin()
        {
            return _str;
        }
        // 尾
        iterator end()
        {
            return _str + _size;
        }
        // 头 const
        const_iterator begin() const
        {
            return _str;
        }
        // 尾 const
        const_iterator end() const
        {
            return _str + _size;
        }

        // insert插入字符函数
        string &insert(size_t pos, char ch)
        {
            assert(pos <= _size);

            // 满了就扩容
            if (_size == _capacity)
                reserve(_capacity == 0 ? 4 : _capacity * 2);

            size_t end = _size + 1;
            while (end > pos)
            {
                _str[end] = _str[end - 1];
                --end;
            }

            _str[pos] = ch;
            ++_size;

            return *this;
        }

        // insert插入字符串函数
        string &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 + len;
            while (end >= pos + len)
            {
                _str[end] = _str[end - len];
                --end;
            }
            // 拷贝内容
            strncpy(_str + pos, str, len);
            _size += len;

            return *this;
        }
        // 删除len个字符
        void erase(size_t pos, size_t len = npos)
        {
            assert(pos < _size);

            if (len == npos || pos + len >= _size)
            {
                _str[pos] = '\0';
                _size = pos;
            }
            else
            {
                strcpy(_str + pos, _str + pos + len);
                _size -= len;
            }
        }

        // 预留空间
        void reserve(size_t n)
        {
            if (n > _capacity)
            {
                char *tmp = new char[n + 1]; // 开新空间
                strcpy(tmp, _str);           // 拷贝内容
                delete[] _str;               // 释放原空间

                _str = tmp;    // 更新指针指向
                _capacity = n; // 拷贝容量
            }
        }

        // 预留空间 + 初始化
        void resize(size_t n, char ch = '\0')
        {
            if (n > _size)
            {
                // 插入数据
                reserve(n);
                for (size_t i = _size; i < n; ++i)
                {
                    _str[i] = ch;
                }
                _str[n] = '\0';
                _size = n;
            }
            else
            {
                // 删除数据
                _str[n] = '\0';
                _size = n;
            }
        }

        // 插入字符 push_back
        void push_back(char ch)
        {
            insert(_size, ch);
        }

        // 插入字符串 append
        void append(const char *str)
        {
            insert(_size, str);
        }

        void append(const string &s)
        {
            append(s._str);
        }
        
        void append(size_t n, char ch)
        {
            reserve(_size + n);
            for (size_t i = 0; i < n; ++i)
            {
                push_back(ch);
            }
        }

        // +=字符
        string &operator+=(char ch)
        {
            push_back(ch);
            return *this;
        }
        // +=字符串
        string &operator+=(const char *str)
        {
            append(str);
            return *this;
        }

        // 清空字符串
        void clear()
        {
            _str[0] = '\0';
            _size = 0;
        }

        // find函数查找字符
        size_t find(char ch, size_t pos = 0) const
        {
            assert(pos < _size);

            for (size_t i = pos; i < _size; ++i)
            {
                if (ch == _str[i])
                {
                    return i;
                }
            }

            return npos;
        }

        // find函数查找字符串
        size_t find(const char *sub, size_t pos = 0) const
        {
            assert(sub);
            assert(pos < _size);

            const char *ptr = strstr(_str + pos, sub);
            if (ptr == nullptr)
            {
                return npos;
            }
            else
            {
                return ptr - _str;
            }
        }

        // substr函数 从pos处取len个字符作为子串返回
        string substr(size_t pos, size_t len = npos) const
        {
            assert(pos < _size);
            size_t realLen = len;
            if (len == npos || pos + len > _size)
            {
                realLen = _size - pos;
            }

            string sub;
            for (size_t i = 0; i < realLen; ++i)
            {
                sub += _str[pos + i];
            }

            return sub;
        }

        // 比较大小
        bool operator>(const string &s) const
        {
            return strcmp(_str, s._str) > 0;
        }
        // 比较相等
        bool operator==(const string &s) const
        {
            return strcmp(_str, s._str) == 0;
        }
        // 判断 >=
        bool operator>=(const string &s) const
        {
            return *this > s || *this == s;
        }
        // 判断 <=
        bool operator<=(const string &s) const
        {
            return !(*this > s);
        }
        // 判断 <
        bool operator<(const string &s) const
        {
            return !(*this >= s);
        }
        // 判断 !=
        bool operator!=(const string &s) const
        {
            return !(*this == s);
        }
    };

    ostream &operator<<(ostream &out, const string &s)
    {
        for (size_t i = 0; i < s.size(); ++i)
            out << s[i];
        return out;
    }
    // 流提取--类比缓冲区 优化代码
    istream &operator>>(istream &in, string &s)
    {
        s.clear();

        char ch;
        ch = in.get();

        const size_t N = 32;
        char buff[N];
        size_t i = 0;

        while (ch != ' ' && ch != '\n')
        {
            buff[i++] = ch;
            if (i == N - 1)
            {
                buff[i] = '\0';
                s += buff;
                i = 0;
            }

            ch = in.get();
        }

        buff[i] = '\0';
        s += buff;

        return in;
    }
}

测试函数

cpp 复制代码
#include "mini_string.hpp"
namespace king
{
    // 构造、下标访问
    void test_string1()
    {
        // 构造
        string s1("hello world");
        string s2; // 若使用无参构造1.0无法输出
        // c_str
        cout << s1.c_str() << endl;
        cout << s2.c_str() << endl;
        // 下标访问
        for (size_t i = 0; i < s1.size(); ++i)
        {
            cout << s1[i] << " ";
        }
        cout << endl;
        // 下标访问const
        for (size_t i = 0; i < s1.size(); ++i)
        {
            s1[i]++;
            cout << s1[i] << " ";
        }
    }

    // 迭代器
    void test_string2()
    {
        // 迭代器访问
        string s1("hello world");
        string::iterator it = s1.begin();
        while (it != s1.end())
        {
            *it += 1;
            cout << *it << " ";
            ++it;
        }
        cout << endl;

        // 迭代器--范围for
        for (auto ch : s1)
        {
            cout << ch << " ";
        }
        cout << endl;
    }

    // 拷贝构造
    void test_string3()
    {
        string s1("hello world");
        string s2(s1);
        cout << s1.c_str() << endl;
        cout << s2.c_str() << endl;

        s2[0] = 'x';
        cout << s1.c_str() << endl;
        cout << s2.c_str() << endl;

        string s3("111111111111111111111111111111");

        s1 = s3;
        // 默认的赋值存在的问题:
        // 1.s1._str指向空间的地址丢失
        // 2.对同一块空间析构两次

        cout << s1.c_str() << endl;
        cout << s3.c_str() << endl;

        s1 = s1;
        cout << s1.c_str() << endl;
        cout << s3.c_str() << endl;
    }

    // 两个swap函数

    // 增加字符
    void test_string5()
    {
        string s1("hello");
        cout << s1.c_str() << endl;
        s1.push_back('x');
        cout << s1.c_str() << endl;
        cout << s1.capacity() << endl;

        s1 += 'y';
        s1 += 'z';
        s1 += 'z';
        s1 += 'z';
        s1 += 'z';
        s1 += 'z';
        s1 += 'z';
        cout << s1.c_str() << endl;
        cout << s1.capacity() << endl;
    }

    // 增加字符串
    void test_string6()
    {
        string s1("hello");
        cout << s1.c_str() << endl;
        s1 += ' ';
        s1.append("world");
        s1 += "bit hello";
        cout << s1.c_str() << endl;
    }

    // 插入字符、字符串
    void test_string7()
    {
        string s1("hello");
        cout << s1.c_str() << endl;

        s1.insert(5, '#');
        cout << s1.c_str() << endl;

        s1.insert(0, '#');
        cout << s1.c_str() << endl;

        s1.insert(2, "world");
        cout << s1.c_str() << endl;

        s1.insert(0, "world ");
        cout << s1.c_str() << endl;
    }

    // 删除字符、字符串
    void test_string8()
    {
        string s1("hello");
        s1.erase(1, 10);
        cout << s1.c_str() << endl;

        string s2("hello");
        s2.erase(1);
        cout << s2.c_str() << endl;

        string s3("hello");
        s3.erase(1, 2);
        cout << s3.c_str() << endl;
    }

    // 流插入、流提取
    void test_string9()
    {
        string s1("hello");
        cout << s1 << endl;
        cout << s1.c_str() << endl;
        s1 += '\0';
        s1 += "world";
        cout << s1 << endl;
        cout << s1.c_str() << endl;

        string s3, s4;
        cin >> s3 >> s4;
        cout << s3 << s4 << endl;
    }

    // find、substr
    void DealUrl(const string &url)
    {
        size_t pos1 = url.find("://");
        if (pos1 == string::npos)
        {
            cout << "非法url" << endl;
            return;
        }
        string protocol = url.substr(0, pos1);
        // 从网址首部取pos1个字符作为子串
        cout << protocol << endl;

        size_t pos2 = url.find('/', pos1 + 3);
        if (pos2 == string::npos)
        {
            cout << "非法url" << endl;
            return;
        }
        string domain = url.substr(pos1 + 3, pos2 - pos1 - 3);
        cout << domain << endl;

        string uri = url.substr(pos2 + 1);
        cout << uri << endl
             << endl;
    }
    void test_string10()
    {
        string url1 = "https://cplusplus.com/reference/string/string/";
        string url2 = "ftp://ftp.cs.umd.edu/pub/skipLists/skiplists.pdf";

        DealUrl(url1);
        DealUrl(url2);
    }

    // resize函数:开空间 + 初始化
    void test_string11()
    {
        string s1;
        s1.resize(20);

        string s2("hello");
        s2.resize(20, 'x');

        s2.resize(10);
    }

    // vs对于string类的优化
    void test_string12()
    {
        std::string s0;
        std::string s1("111111");
        std::string s2("11111111111111111111111111111111111111111");
        cout << sizeof(s0) << endl; // 40
        cout << sizeof(s1) << endl; // 40
        cout << sizeof(s2) << endl; // 40

        // 理论上:sizeof(s) == 12
        // 实  际:string还有第4个成员变量
        // 不同vs版本不同 此VS2022下:char _buff[28]
        //_size <  28 :字符串存放在_buff数组中
        //_size >= 28 :            _str指向的堆空间上
    }
}

void test_string4()
{
    string s1("hello world");
    string s2("xxxxxxx");

    // s1.swap(s2);
    // 模拟实现string类的成员函数:void swap(string& t)
    //==>   原string类的成员函数:void std::string::swap(string & str);
    // 作用:交换类的成员变量(_str交换地址)
    s1.swap(s2);

    // 全局域的swap函数:
    /*
    template <class T>
    void std::swap(T & a, T & b);
    {
        T c(a);
        a = b;
        b = a;
    }
    */
    // 作用:经历了拷贝构造+赋值运算 a b 的_str指向空间的地址均被更新

    std::swap(s1, s2);
    ::swap(s1, s2);
}

int main()
{
    king::test_string1();
    return 0;
}
相关推荐
蜡笔小新星7 分钟前
Flask项目框架
开发语言·前端·经验分享·后端·python·学习·flask
IT猿手8 分钟前
2025最新群智能优化算法:海市蜃楼搜索优化(Mirage Search Optimization, MSO)算法求解23个经典函数测试集,MATLAB
开发语言·人工智能·算法·机器学习·matlab·机器人
夏天的味道٥3 小时前
使用 Java 执行 SQL 语句和存储过程
java·开发语言·sql
海鸥814 小时前
查看k8s集群的资源使用情况
云原生·容器·kubernetes
云上艺旅4 小时前
K8S学习之基础十八:k8s的灰度发布和金丝雀部署
学习·云原生·容器·kubernetes
IT、木易4 小时前
大白话JavaScript实现一个函数,将字符串中的每个单词首字母大写。
开发语言·前端·javascript·ecmascript
Mr.NickJJ5 小时前
JavaScript系列06-深入理解 JavaScript 事件系统:从原生事件到 React 合成事件
开发语言·javascript·react.js
Dream it possible!5 小时前
LeetCode 热题 100_字符串解码(71_394_中等_C++)(栈)
c++·算法·leetcode
Archer1946 小时前
C语言——链表
c语言·开发语言·链表
My Li.6 小时前
c++的介绍
开发语言·c++