zoukankan      html  css  js  c++  java
  • c++简单实现string类

    View Code
    #include<iostream>
    #include
    <cstring>
    using namespace std;

    class mystring
    {
    public:
    mystring(
    char *s);
    mystring();
    ~mystring();//虚构函数用来释放动态内存
    void addstring(char *s);//连接两个字符串
    void stringup(char *s);//字符串大写换小写
    void change(char *s);//改变字符串
    void show();//输出字符串
    private:
    int len;
    char *p;
    };

    mystring::mystring(
    char *s)
    {
    len
    =strlen(s);
    p
    =new char [len+1];
    strcpy(p,s);
    }

    mystring::mystring()
    {
    len
    =0;
    p
    =new char [len+1];
    }

    mystring::
    ~mystring()
    {
    delete []p;
    len
    =0;
    }

    void mystring::addstring(char *s)
    {
    int tlen=strlen(s);
    char *temp=new char [len+1];

    strcpy(temp,p);

    delete []p;
    p
    =new char [len+tlen+1];//p的动态内存重新申请
    strcpy(p,temp);
    strcat(p,s);

    delete temp;
    //释放临时动态内存
    }

    void mystring::stringup(char *s)
    {
    int i;
    if(p!=NULL)
    delete []p;
    len
    =strlen(s);
    p
    =new char [len+1];
    strcpy(p,s);

    for(i=0;i<len;i++)
    {
    if(p[i]>='a'&&p[i]<='z')
    {
    //s[i]=s[i]-32;b不行
    p[i]=s[i]-32;

    }
    }
    }

    void mystring::change(char *s)
    {
    delete []p;
    len
    =strlen(s);
    p
    =new char [len+1];
    strcpy(p,s);
    }

    void mystring::show()
    {
    cout
    <<p<<endl;
    }

    void main()
    {
    mystring ms(
    "awdseswsa");
    ms.show();

    ms.addstring(
    "123");
    ms.show();

    ms.change(
    "dedede");
    ms.show();

    ms.stringup(
    "abc");
    ms.show();
    }
  • 相关阅读:
    python 协程
    python 进程池的使用
    python 多进程数据交互及共享
    python 多进程
    技术博客与技术日记
    理解闭包
    jWriter一个基于jQuery的阅读写作网站的效果库
    ubuntu下phpmyadmin配置问题解决
    避免明文保存用户密码
    如何用css实现类似简书的纵向导航/竖排导航
  • 原文地址:https://www.cnblogs.com/huhuuu/p/2019047.html
Copyright © 2011-2022 走看看