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;
}
相关推荐
Predestination王瀞潞1 小时前
IO操作(Num22)
开发语言·c++
haoly19892 小时前
数据结构和算法篇-线性查找优化-移至开头策略
数据结构·算法·移至开头策略
宋恩淇要努力3 小时前
C++继承
开发语言·c++
沿着路走到底4 小时前
python 基础
开发语言·python
沐知全栈开发5 小时前
C# 委托(Delegate)
开发语言
江公望5 小时前
Qt qmlRegisterSingletonType()函数浅谈
c++·qt
任子菲阳5 小时前
学Java第三十四天-----抽象类和抽象方法
java·开发语言
学Linux的语莫6 小时前
机器学习数据处理
java·算法·机器学习
csbysj20206 小时前
如何使用 XML Schema
开发语言
R6bandito_6 小时前
STM32中printf的重定向详解
开发语言·经验分享·stm32·单片机·嵌入式硬件·mcu