C++ day3

题目:仿照string类,实现myString

cpp 复制代码
#include <iostream>
#include <cstring> 
using namespace std;
//仿照string完成myString类
class myString
{
    private:
        char *str;          //记录c风格的字符串
        int size;            //记录分配的内存大小
        int len;          //字符串长度
    public:
        //无参构造
        myString():size(10),len(0)
        {
            str = new char[size]; //构造出一个长度为10的字符串
            str[0]='\0';
        }
        //有参构造
        myString(const char *s): len(strlen(s)), size(len + 1)        //有参构造     string  s("hello wirld");
        {
            str = new char[size];
            strcpy(str,s);
        }
        //析构函数
        ~myString()
        {
            delete [] str;
        }
        //判空函数
        bool empty()
        {
            return len==0;
        }
        //size函数
        int get_size()
        {
            return size;
        }
        //或许字符串长度
        int get_len()
        {
            return len;
        }
        //c_str函数
        const char* c_str()
        {
            return str;
        }

        //at函数
        char &at(int index)
        {
            if (index < 0 || index >=len)
            {
                 throw std::out_of_range("查找范围错误");
            }
           return str[index];
        }
        //二倍扩容
        void resize(int newSize)
        {
               if (newSize > size)
               {
                   char *newStr = new char[newSize];
                   std::strcpy(newStr, str);
                   delete[] str;
                   str = newStr;
                   size = newSize;
               }
        }
};

int main()
{
    myString s("Hello, World!");
        std::cout << s.c_str() << std::endl;
        std::cout << "len: " << s.get_len() << std::endl;
        std::cout << "Size: " << s.get_size() << std::endl;

        std::cout << "第七个字符为: " << s.at(7) << std::endl;

    return 0;
}
相关推荐
lly20240613 小时前
《堆的 shift down》
开发语言
cpp_250113 小时前
P10570 [JRKSJ R8] 网球
数据结构·c++·算法·题解
cpp_250113 小时前
P8377 [PFOI Round1] 暴龙的火锅
数据结构·c++·算法·题解·洛谷
黎雁·泠崖13 小时前
【魔法森林冒险】2/14 抽象层设计:Figure/Person类(所有角色的基石)
java·开发语言
uesowys13 小时前
Apache Spark算法开发指导-Factorization machines classifier
人工智能·算法
程序员老舅14 小时前
C++高并发精髓:无锁队列深度解析
linux·c++·内存管理·c/c++·原子操作·无锁队列
划破黑暗的第一缕曙光14 小时前
[C++]:2.类和对象(上)
c++·类和对象
季明洵14 小时前
C语言实现单链表
c语言·开发语言·数据结构·算法·链表
shandianchengzi14 小时前
【小白向】错位排列|图文解释公考常见题目错位排列的递推式Dn=(n-1)(Dn-2+Dn-1)推导方式
笔记·算法·公考·递推·排列·考公
I_LPL14 小时前
day26 代码随想录算法训练营 回溯专题5
算法·回溯·hot100·求职面试·n皇后·解数独