C++初阶:string类模拟实现

本节内容主要针对的是在STL之前的string类的实现,通过模拟实现string类的一些功能来更好地使用string。本篇主要针对的是非const对象,如果要实现const的对象的话,只需要在对应的部分增添上const就行了。编者水平有限,如有错误欢迎指正。

目录

1.String.h

2.Test.cpp


1.String.h

cpp 复制代码
#include <iostream>
#include <cstring>
#include <cassert>
using namespace std;
class String
{
    
    friend istream& getline(istream &in, String &s);
    friend ostream& operator<<(ostream&out,String&s);
    friend istream& operator>>(istream &in, String &s);
public: 
    static const size_t npos = -1;
    // 实现迭代器
    typedef char *iterator;
    typedef const char *const_iterator;
    iterator begin()
    {
        return _str;
    }
    iterator end()
    {
        return _str + _size;
    }
    const_iterator begin() const
    {
        return _str;
    }
    const_iterator end() const
    {
        return _str + _size;
    }
    // 构造
    String(const char *str = "");
    // 析构
    ~String();
    //拷贝构造
    String(const String& s);
    // 获取长度
    size_t size() const;
    // 获取容器容量
    size_t capacity() const;
    // 访问元素
    char &operator[](size_t pos);
    // 获取字符数组
    const char *c_str() const;
    // 容量预设
    void reserve(size_t n);
    // 调整大小
    void resize(size_t n, char c = '\0');
    // 尾插字符
    void push_back(char c);
    // 尾插字符串
    void append(const char *s);
    // 尾插数据
    String &operator+=(const char *s);
    String &operator+=(char c);
    // 清除数据
    String &erase(size_t pos = 0, size_t len = npos);
    // 查找字符或子串
    size_t find(char c, size_t pos = 0) const;
    size_t find(const char *s, size_t pos = 0) const;
    // 取子串
    String substr(size_t pos = 0, size_t len = npos) const;
    // 清除
    void clear();
    // 交换
    void swap(String &s);
    // 插入
    String &insert(size_t pos, char c);
    String &insert(size_t pos, const char *s);
    
    // 重载
    String operator+(const char* s);
    String &operator=(const String &s);
    bool operator>(const String& s);
    bool operator<(const String& s);
    bool operator==(const String& s);
    
private:
    // 长度
    int _size;
    // 容量
    int _capacity;
    // 内容
    char *_str;
};
istream& getline(istream &in, String &s)
{
    //先对原字符串进行清空
    s.clear();
    //然后获取字符,填充buff数组
    char ch;
    ch = in.get();
    char buff[128];
    size_t i = 0;
    //取到'\n'截止
    while (ch != '\n')
    {
        buff[i++] = ch;
        //如若数组到头了,就将最后一个字符置为'\0',并将字符数组的值赋予给String对象
        if (i == 127)
        {
            buff[127] = '\0';
            s += buff;
            i = 0;
        }

        ch = in.get();
    }

    if (i > 0)
    {
        buff[i] = '\0';
        s += buff;
    }
    return in;
}

ostream& operator<<(ostream&out,String&s)
{
    out<<s._str<<endl;
    return out;
}

istream& operator>>(istream&in,String&s)
{
    //先对原字符串进行清空
    s.clear();
    //然后获取字符,填充buff数组
    char ch;
    ch = in.get();
    char buff[128];
    size_t i = 0;
    //取到' '或者'\n'截止
    while (ch != ' ' && ch != '\n')
    {
        buff[i++] = ch;
        //如若数组到头了,就将最后一个字符置为'\0',并将字符数组的值赋予给String对象
        if (i == 127)
        {
            buff[127] = '\0';
            s += buff;
            i = 0;
        }

        ch = in.get();
    }

    if (i > 0)
    {
        buff[i] = '\0';
        s += buff;
    }

    return in;
}

String::String(const char *str) : _size(strlen(str))
{
    //初始容量即为初始长度
    _capacity = _size;
    //开辟空间应该比_capacity多1个用来存储'\0'
    _str = new char[_capacity + 1];
    //拷贝数值
    strcpy(_str, str);
}

String::~String()
{
    //防止二次释放
    if(_str)
    {
        delete[] _str;
        _str = nullptr;
        _size = _capacity = 0;
    }
}

String::String(const String &s)
{
    //道理同构造函数
    _size = s._size;
    _capacity = s._capacity;
    _str = new char[_capacity + 1];
    strcpy(_str, s._str);
}

size_t String::size() const
{
    return _size;
}

size_t String::capacity() const
{
    return _capacity;
}

char &String::operator[](size_t pos)
{
    assert(pos < _size);
    return _str[pos];
}

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

void String::reserve(size_t n)
{
    // 扩容,如果n大于_capacity,就扩容并挪动数据
    assert(n > 0);
    if (n > _capacity)
    {
        char *temp = new char[n + 1];
        strcpy(temp, _str);
        delete[] _str;
        _str = temp;
        _capacity = n;
    }
}

void String::resize(size_t n, char c)
{
    // 如果n小于了目前的长度,则从n起的所有元素被清除,大于目前的长度则扩容
    if (n <= _size)
    {
        _str[n] = '\0';
        _size = n;
    }
    else
    {
        reserve(n);
        for (int i = _size; i < n; i++)
        {
            _str[i] = c;
        }
        _str[n] = '\0';
        _size = n;
    }
}

void String::push_back(char c)
{
    if (_size == _capacity)
    {
        reserve(_capacity == 0 ? 4 : _capacity * 2);
    }
    _str[_size++] = c;
    _str[_size] = '\0';
}

void String::append(const char *s)
{
    int len = strlen(s);
    if (len + _size > _capacity)
    {
        reserve(len + _size);
    }
    strcpy(_str + _size, s);
    _size += len;
}

String &String::operator+=(const char *s)
{
    append(s);
    return *this;
}

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

String &String::erase(size_t pos, size_t len)
{
    assert(pos < _size);
    // 如果清除长度大于剩余长度,则一次性清完,否则擦除了之后就把剩下的copy到后面去
    if (pos + len >= _size || len == npos)
    {
        _str[pos] = '\0';
        _size = pos;
    }
    else
    {
        strcpy(_str + pos, _str + pos + len);
        _size -= len;
    }
    return *this;
}

size_t String::find(char c, size_t pos) const
{
    // 找到了返回相对于起点的定位索引,找不到返回npos
    for (int i = pos; i < _size; i++)
    {
        if (c == _str[i])
        {
            return i;
        }
    }
    return npos;
}

size_t String::find(const char *s, size_t pos) const
{
    // 找到了返回相对于起点的定位索引,找不到返回npos
    const char *p = strstr(_str + pos, s);
    if (p)
    {
        return p - _str;
    }
    else
    {
        return npos;
    }
}

String String::substr(size_t pos, size_t len) const
{
    String sub;
    // 判断所取长度是否超过了剩余长度,是则直接取完,否则按需所取
    if (len == npos || len >= _size - pos)
    {
        for (size_t i = pos; i < _size; i++)
        {
            sub += _str[i];
        }
    }
    else
    {
        for (size_t i = pos; i < pos + len; i++)
        {
            sub += _str[i];
        }
    }

    return sub;
}

void String::clear()
{
    // 直接置为0即可
    _size = 0;
    _str[_size] = '\0';
}

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

String &String::insert(size_t pos, char c)
{
    assert(pos <= _size);
    // 检查容量
    if (_size = _capacity)
    {
        reserve(_capacity == 0 ? 4 : _capacity * 2);
    }
    // 挪动数据
    size_t index = _size + 1;
    while (index > pos)
    {
        _str[index] = _str[index - 1];
        index--;
    }
    // 添加数据
    _str[pos] = c;
    _size++;
    return *this;
}

String &String::insert(size_t pos, const char *s)
{
    assert(pos <= _size);
    // 先检查容量,挪动数据
    size_t len = strlen(s);
    if (len > _capacity - _size)
    {
        reserve(_capacity + len);
    }
    // 接着将数据从pos位置后移strlen(s)个单位
    size_t end = _size + len;
    while (end > pos + len - 1)
    {
        _str[end] = _str[end - len];
        end--;
    }
    // 最后使用strncpy把s中的数据copy进去
    strncpy(_str + pos, s, len);
    _size += len;
    return *this;
}

String String::operator+(const char*s)
{
    //erro 浅拷贝导致同一块空间被多次delete(已订正)
    String temp=*this;
    temp+=s;
    return temp;
}

String &String::operator=(const String &s)
{
    //道理同拷贝构造,但是需要将原来指向的空间delete
    _size = s._size;
    _capacity = s._capacity;
    delete[]_str;
    _str = new char[_capacity + 1];
    strcpy(_str, s._str);
    return *this;
}

bool String::operator>(const String &s)
{
    if(strcmp(_str,s._str)>0)
        return true;
    return false;
}

bool String::operator<(const String &s)
{
    if(strcmp(_str,s._str)<0)
        return true;
    return false;
}

bool String::operator==(const String &s)
{
    if(strcmp(_str,s._str)==0)
        return true;
    return false;
}

2.Test.cpp

cpp 复制代码
#include "String.h"
void Test1()
{
    String a1;
    String a2("hahaha");
    cout << a2[1] << endl;
    cout << a2[0] << endl;
    cout << a2.size() << endl;
    cout << a2.capacity() << endl;
}
void Test2()
{
    String a1("ssDut");
    cout << a1.c_str() << endl;
    a1.reserve(3);
    cout << a1.capacity() << endl;
    a1.reserve(20);
    cout << a1.capacity() << endl;
    a1.resize(0);
    cout << a1.c_str() << endl;
    a1.resize(23, 'a');
    cout << a1.capacity() << endl;
    cout << a1.c_str() << endl;
}
void Test3()
{
    String a1("hello world");
    cout << a1.c_str() << endl;
    cout << a1.capacity() << endl;
    cout << a1.size() << endl;

    // a1.push_back('a');
    // a1.push_back('a');
    // a1.push_back('a');
    // a1.push_back('a');
    // a1.push_back('a');
    // a1.push_back('a');
    // a1.push_back('a');
    // a1.push_back('a');
    // a1.push_back('a');
    // a1.push_back('a');
    // a1.push_back('a');
    // cout<<a1.c_str()<<endl;
    // cout<<a1.capacity()<<endl;
    // cout<<a1.size()<<endl;
    a1.append("Qinhan");
    cout << a1.c_str() << endl;
    cout << a1.capacity() << endl;
    cout << a1.size() << endl;
}
void Test4()
{
    String a1("I bite you");
    // (a1+="r mother")+="Timi";
    cout << a1.c_str() << endl;
    cout << a1.capacity() << endl;
    cout << a1.size() << endl;
    a1.erase(3, 4);
    cout << a1.c_str() << endl;
    cout << a1.capacity() << endl;
    cout << a1.size() << endl;
    a1.erase();
    cout << a1.c_str() << endl;
    cout << a1.capacity() << endl;
    cout << a1.size() << endl;
    // a1.erase(10, 10);
    // cout << a1.c_str() << endl;
    // cout << a1.capacity() << endl;
    // cout << a1.size() << endl;
}
void Test5()
{
    String a1("I bite you");
    for(auto e:a1)
    {
        cout<<e<<endl;
    }
    cout<<"------------------------------------------------------------"<<endl;
    // a1.insert(10,'c');
    // a1.insert(2,"happy day");
    // for(auto e:a1)
    // {
    //     cout<<e<<endl;
    // }
    // cout<<(int)a1._str[a1._size]<<endl;
}
void Test6()
{
    String a1("I bite you");
    String a2=a1+"r mom";
    for(auto e:a2)
    {
        cout<<e;
    }
    cout<<endl;
    cout<<(a1<a2)<<endl;
}
void Test7()
{
    String s1("Hello");
    cout<<s1;
    // cin>>s1;
    getline(cin,s1);
    cout<<s1;
}
int main()
{
    Test7();
    return 0;
}
相关推荐
风清扬_jd几秒前
Chromium 中JavaScript Fetch API接口c++代码实现(二)
javascript·c++·chrome
liu_chunhai9 分钟前
设计模式(3)builder
java·开发语言·设计模式
姜学迁17 分钟前
Rust-枚举
开发语言·后端·rust
冷白白19 分钟前
【C++】C++对象初探及友元
c语言·开发语言·c++·算法
凌云行者23 分钟前
rust的迭代器方法——collect
开发语言·rust
It'sMyGo26 分钟前
Javascript数组研究09_Array.prototype[Symbol.unscopables]
开发语言·javascript·原型模式
睡觉然后上课37 分钟前
c基础面试题
c语言·开发语言·c++·面试
qing_04060344 分钟前
C++——继承
开发语言·c++·继承
武昌库里写JAVA44 分钟前
【Java】Java面试题笔试
c语言·开发语言·数据结构·算法·二维数组
ya888g1 小时前
GESP C++四级样题卷
java·c++·算法