【C++】仿照string类,实现myString

仿照string类,实现myString

main.c

#include"myString.h"

int main()
{
    myString s1("hello world");
    cout<<"字符串长度位:"<<s1.str_size()<<" C语言格式输出"<<s1.c_str()<<endl;
    cout<<"第7个字符是:";
    s1.at(7);
    s1.set("zxy是最帅的人不接受反驳");//修改字符串
    s1.show();//查看是否修改成功
    return 0;
}

myString.c

#include"myString.h"
//判空函数
bool myString::empty()
{
    return size;
}
//set函数修改字符串的内容
void myString::set(const char *s)
{
    strcpy(str,s);//复制内容
    expend();//判断是否需要扩容
    strcpy(str,s);//如果扩容代表第一次可能没复制成功,重新复制一边
}
//size函数
int myString::str_size()
{
    return strlen(str);
}
//c_str函数
const char* myString::c_str()
{
    expend();
    str[str_size()]= '\0';
    return str;
}
//at函数
myString &myString::at(int index)
{
    if(index < 1 || index > str_size())
    {
        cout<<"下标不合理"<<endl;
    }
    expend();
    cout<<str[index-1]<<endl;
}
//二倍扩容
void myString::expend()
{
    char *temp;
    //说明申请的空间已经用完了,需要扩容
    if(str_size() >= size)
    {
        size = size*2;
        temp = new char[size];
        strcpy(temp,str);
        delete str;
        str = temp;
    }
}
//展示函数
void myString::show()
{
    cout<<str<<endl;
}

myString.h

#ifndef MYSTRING_H
#define MYSTRING_H
#include <iostream>
#include<cstring>
using namespace std;
class myString
{
private:
    char *str;   //记录字符串
    int size;    //记录字符串的长度
    
public:
    myString():size(10)
    {
        str = new char[size];//堆区申请空间大小为size
    }
    //有参构造
    myString(const char *s)  //有参构造
    {
        size = strlen(s);
        str = new char[size];
        strcpy(str,s);
    }
    //判空函数
    bool empty();
    //set函数修改字符串的内容
    void set(const char *s);
    //size函数
    int str_size();
    //c_str函数
    const char* c_str();
    //at函数
    myString &at(int index);
    //二倍扩容
    void expend();
    //展示函数
    void show();
};
#endif // MYSTRING_H

运行效果展示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值