C++复习 - String

自己实现String类

cpp 复制代码
#include <iostream>
#include <cassert>
#include <cstring>


namespace whxnchy {
    class string {
    public:
        typedef char* iterator;

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

        // 拷贝构造函数
        string(const string& s)
            : _str(nullptr), _size(0), _capacity(0) {
            string tmp(s._str);
            (*this).swap(tmp);
        }

        // 赋值运算符的重载
        string& operator=(string s) {
            this->swap(s);
            return *this;
        }

        // 析构函数
        ~string() {
            if (_str) {
                delete[] _str;
                _str = nullptr;
            }
        }

        // 迭代器
        iterator begin() { return _str; }
        iterator end() { return _str + _size; }

        // 修改操作
        void push_back(char c) {
            if (_size == _capacity)
                reserve(_capacity * 2);
            _str[_size++] = c;
            _str[_size] = '\0';
        }

        string& operator+=(char c) {
            push_back(c);
            return *this;
        }

        void append(const char* str) {
            size_t len = strlen(str);
            if (_size + len > _capacity)
                reserve(_size + len);
            strcpy(_str + _size, str);
            _size += len;
        }
       

        string& operator+=(const char* str)
        {
            append(str);
            return *this;
        }

        void clear() {
            _size = 0;
            _str[_size] = '\0';
        }

        void swap(string& s) {
            std::swap(_str, s._str);
            std::swap(_size, s._size);
            std::swap(_capacity, s._capacity);
        }

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

        // 容量
        size_t size()  const {
            return _size;
        }

        size_t capacity() const {
            return _capacity;
        }

        bool empty() const {
            return _size == 0;
        }

       
        void resize(size_t newSize, char c = '\0') {
            if (newSize > _size) {
                if (newSize > _capacity)
                    reserve(newSize);
                memset(_str + _size, c, newSize - _size);
            }
            _size = newSize;
            _str[newSize] = '\0';
        }
        void reserve(size_t newCapacity)
        {
            if (newCapacity > _capacity) {
                char* newStr = new char[newCapacity + 1];
                strcpy(newStr, _str);
                delete[] _str;
                _str = newStr;
                _capacity = newCapacity;
            }
        }
        // 访问
        char& operator[](size_t index) {
            assert(index < _size);
            return _str[index];
        }

        const char& operator[](size_t index) const {
            assert(index < _size);
            return _str[index];
        }

        // 比较运算符
        bool operator<(const string& s) 
        {
            return strcmp(_str, s._str) < 0;
        }

        bool operator<=(const string& s) {
            return strcmp(_str, s._str) <= 0;
        }

        bool operator>(const string& s) {
            return strcmp(_str, s._str) > 0;
        }

        bool operator>=(const string& s) 
        {
            return !(*this<s);
        }

        bool operator==(const string& s) {
            return strcmp(_str, s._str) == 0;
        }

        bool operator!=(const string& s) {
            return strcmp(_str, s._str) != 0;
        }
        // 查找和操作
        size_t find(char c, size_t pos) const {
            size_t i = pos;
            while (i < _size && _str[i] != c)
                ++i;
            return (i < _size) ? i : std::string::npos;
        }

        size_t find(const char* s, size_t pos) const {
            size_t len = strlen(s);
            if (len == 0)
                return pos;
            if (pos + len > _size)
                return std::string::npos;
            const char* result = strstr(_str + pos, s);
            return result ? result - _str : std::string::npos;
        }

        string& insert(size_t pos, char c) {
            if (pos > _size)
                pos = _size;
            if (_size == _capacity)
                reserve(_capacity * 2);
            memmove(_str + pos + 1, _str + pos, _size - pos + 1);
            _str[pos] = c;
            ++_size;
            return *this;
        }

        string& insert(size_t pos, const char* str) {
            if (pos > _size)
                pos = _size;
            size_t len = strlen(str);
            if (_size + len > _capacity)
                reserve(_size + len);
            memmove(_str + pos + len, _str + pos, _size - pos + 1);
            memcpy(_str + pos, str, len);
            _size += len;
            return *this;
        }

        string& erase(size_t pos, size_t len){
            if (pos >= _size)
                return *this;
            if (pos + len >= _size)
                len = _size - pos;
            memmove(_str + pos, _str + pos + len, _size - pos - len + 1);
            _size -= len;
            return *this;
        }



    private:
        friend std::ostream& operator<<(std::ostream& _cout, const whxnchy::string& s);
        friend std::istream& operator>>(std::istream& _cin, whxnchy::string& s);

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

    std::ostream& operator<<(std::ostream& _cout, const whxnchy::string& s) {
        for (size_t i = 0; i < s.size(); ++i) {
            _cout << s[i];
        }
        return _cout;
    }
}

// 进行测试
void TestBitstring() {
    whxnchy::string s1("hello");
    s1.push_back(' ');
    s1.push_back('b');
    s1.append("it");
    s1 += "'!!'";

    std::cout << s1 << std::endl;
    std::cout << "Size: " << s1.size() << std::endl;
    std::cout << "Capacity: " << s1.capacity() << std::endl;

    whxnchy::string::iterator it = s1.begin();
    while (it != s1.end()) {
        std::cout << *it << " ";
        ++it;
    }
    std::cout << std::endl;

    for (auto ch : s1)
        std::cout << ch << " ";
    std::cout << std::endl;
}

int main() {
    TestBitstring();
    return 0;
}
相关推荐
小则又沐风a8 分钟前
线程的互斥和同步
linux·c++
o0o_-_13 分钟前
【golang/rust】rs-gopls 上手指南|安装、VS Code / Zed 配置与性能对比
开发语言·golang·rust
阿俊-全栈开发19 分钟前
LikeShop 多商户标准版秒杀与优惠券叠加规则的自定义配置二开
开发语言·分布式·golang·likeshop开源商城·likeshop源码
IT枫斗者25 分钟前
缓存和数据库一致性:先更库还是先删缓存,延迟双删怎么落地
java·开发语言·数据库·人工智能·缓存·gateway
Junsir大斗师37 分钟前
华为云平台下safeline【长亭雷池】反向代理实验
开发语言·nginx·安全·华为云
凡人叶枫39 分钟前
数据结构分类与基本类型:线性、非线性、连续与分散
数据结构·c++
风落青芜1 小时前
C++模板初阶:函数模板与类模板
开发语言·数据结构·c++·算法
传奇开心果编程1 小时前
【华为仓颉独特优势】第11课:回到主场——HarmonyOS 上的仓颉:ArkTS 互操作与“宿主问题”的终极答卷
开发语言·华为·harmonyos·编程语言理论·仓颉·cangjie·通用编程语言
纪念 2291 小时前
C++ 算法模板与错题 (枚举)
c++·redis·算法
master3361 小时前
Java 是如何调用 C 语言接口的?native 方法的完整工作原理
java·c语言·开发语言