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();
}
原文地址:https://www.cnblogs.com/huhuuu/p/2019047.html