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;
}
相关推荐
梁辰兴3 分钟前
数据结构:排序
数据结构·算法·排序算法·c·插入排序·排序·交换排序
Murphy_lx4 分钟前
Lambda表达式
开发语言·c++
yangpipi-12 分钟前
C++并发编程-23. 线程间切分任务的方法
开发语言·c++
野犬寒鸦18 分钟前
力扣hot100:搜索二维矩阵 II(常见误区与高效解法详解)(240)
java·数据结构·算法·leetcode·面试
菜鸟得菜22 分钟前
leecode kadane算法 解决数组中子数组的最大和,以及环形数组连续子数组的最大和问题
数据结构·算法·leetcode
爬虫程序猿1 小时前
利用 Java 爬虫获取淘宝商品 SKU 详细信息实战指南
java·开发语言·爬虫
F2E_Zhangmo1 小时前
基于cornerstone3D的dicom影像浏览器 第五章 在Displayer四个角落显示信息
开发语言·前端·javascript
楼田莉子1 小时前
C++算法专题学习——分治
数据结构·c++·学习·算法·leetcode·排序算法