C++实现myString

    字符串是以 '\0' 作为结尾
    实现该定义字符串类的 += 运算符的重载
    不能使用STL,不能使用 C 库的 strcpy 和 strcat 函数,其余的 C 库函数均可使用
    

例如:
      my_string s1 = "abc";
      my_string s2 = "def";
      s1 += s2; // 该操作完成之后,s1 变成 "abcdef"

   由于s1 +=s2    等价于  s1 = s1+s2,我们首先实现strcpy 和 strcat 函数

//字符串的拷贝
char* strcpy(char* t, const char* s)
{
    char *tmp;
    tmp = t;
    //一一拷贝
    while(*s != '\0')
    {
        *t = *s;
        s++;
        t++;        
    }
    *t = '\0';//结束符
    return tmp;
}

//字符串拼接  在src的末尾追加 dest 
char* strcat(char* dest, const char* src)
{  
    //检查输入条件
    if(dest==NULL || src==NULL)
          throw "非法操作"; 

    //让dest指向‘\0’的地址
    while (*dest != '\0')
        ++dest;
    
    //将从dest的'\0'开始,将src的字符一一赋值给dest
    while (*dest = *src)
    {
        ++dest;
        ++src;
    }

    *dest = '\0';
    return dest;
}

class my_string
{
private:
    char* m_ptr;         // 指向一块动态分配的内存空间
    int   m_size = 0;        // m_ptr 所指向的空间中存储的字符串的长度,不包含 '\0'
    int   m_capacity = 0;    // m_ptr 所指向的空间的总的字节数
public:

    //有参构造函数  根据传入字符串进行构造
    my_string(const char* s,int capacity)
    {
        //动态内存分配 以'\0'为结束符所以+1
        m_ptr = new char[strlen(s) + 1]; 
        m_size = strlen(s) + 1;

        m_capacity = m_size + 100000;

        //调用strcpy函数    
        myStrcpy(m_ptr, s);  
    }

    //析构
    ~my_string()
    {
        if (m_ptr)
            delete[] m_ptr;
    }

    //拷贝构造
    my_string(const my_string &s)
    {
        if (this != &s)
        {
            m_ptr = new char[strlen(s.m_ptr) + 1];
            myStrcpy(m_ptr,s.m_ptr);
            m_size = this->m_size;
            m_capacity = this->m_capacity;

        }
    }

    //重载+号  
    my_string operator+=(const my_string &s)
    { 
        int newLen = this->m_size + s.m_size;
        //容量不够,重新开辟空间
        if (newLen < this->m_capacity)
        {
            //重新开辟空间
            char* tmp = new char[newLen + 1];
            this->m_ptr = tmp; //修改指针
            this->m_size = newLen + 1;
            this->m_capacity = newLen + 100001;

            //然后把原来的字符串拷贝过来
            myStrcpy(tmp, m_ptr);
            //最后拼接s
            myStrcat(tmp, s.m_ptr);      
            
        }
        else //直接进行拼接操作
        {   
            this->m_size = newLen;
            myStrcat(this->m_ptr, s.m_ptr);          
          
        }

        my_string newStr(m_ptr,m_capacity); //创建一个字符串
        return newStr;
              
    }


    //获取字符串
    const char* getStr() const
    {
        return m_ptr;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值