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;
}
相关推荐
哥不想学算法2 小时前
【C++】字符串字面量拼接
开发语言·c++
海石2 小时前
1500分的题目,确实有实力,不过还是我略胜一筹
算法·leetcode
海石2 小时前
【记忆化搜索】条条大路通AC,走好适合你的那一条,走到后再考虑走得快
算法·leetcode
gugucoding4 小时前
21. 【C语言】打包不同类型:结构体
c语言·开发语言
Brookty4 小时前
【JavaEE】线程安全(一).4:写块串行保安全、CAS
java·开发语言·java-ee·多线程·线程安全
Jerry4 小时前
LeetCode 151. 反转字符串中的单词
算法
F20226974865 小时前
西门子 PLC 与 C# 通信
开发语言·c#
gugucoding5 小时前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
万联WANFLOW6 小时前
多分支企业组网,IP 网段到底该怎么规划
开发语言·php