【无标题】

在这里插入图片描述

#include <iostream>
#include <cstring>
using namespace std;
class MyString{
    char *str=nullptr;
    int size=0;
    int capacity=0;
    void reallocSize(int new_len){
        if(new_len>capacity)
            capacity=(capacity+1)*2;
        if(str!=nullptr)
            delete[] str;
        size=new_len-1;
        str=new char[capacity];
    }
public:
    MyString(){
        reallocSize(1);
        str[0]='\0';
    }
    MyString(const MyString &other){
        reallocSize(other.size+1);
        memcpy(str,other.str,other.size+1);
    }
    MyString(int size){
        reallocSize(size);
    }
    MyString(char* s){
        reallocSize(sizeof(s)+1);
        memcpy(str,s,strlen(s)+1);

    }
    const MyString operator=(const MyString &other)const{
        MyString temp(other);
        memcpy(this->str,other.str,other.size+1);
        return temp;
    }
    int length(){return size;}
    const MyString operator+(const MyString &other)const{
        MyString temp(this->size+other.size+1);
        memcpy(temp.str,this->str,this->size);
        memcpy(temp.str+this->size,other.str,other.size+1);
        return temp;
    }
    int compare(const MyString &other)const{
        for(int i=0;i<this->size&&i<other.size;i++)
            if(this->str[i]!=other.str[i]) return this->str[i] > other.str[i] ? 1 : -1;
        return 0;
    }
    ~MyString(){
        delete[] str;
        str=nullptr;
    }
    friend std::ostream& operator<<(std::ostream& os,const MyString& other){
        for(int i=0;i<other.size;i++){
            os<<other.str[i];
        }
        return os;
    }
    friend std::istream& operator>>(std::istream& is,MyString& other){
        is>>other.str;
        other.size=strlen(other.str);
        return is;
    }
    void show(){
        cout<<this->str<<endl;
    }
};

int main()
{
    MyString s1;
    MyString s2("12345678");
    MyString s3("123456");
    MyString s4("123");
    s1.show(),s2.show();
    cout<<s2.compare(s3)<<endl;
    cout<<s2.length()<<endl;
    cout<<s2<<endl;
    cout<<s3+s4<<endl;
    s2=s4;
    cout<<s2<<endl;
    MyString s5(20);
    cin>>s5;
    cout<<s5<<endl;
    return 0;
}

在这里插入图片描述

在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值