📄 3.8cstring.cpp
字号:
#include<iostream.h>
//#include<string.h>
class CString
{
public:
CString(int n=1);
CString(char *s);
CString(const CString &s);
CString &operator=(const CString &s);
~CString();
CString operator+(const CString &sa);
CString operator+(const char *s);//s3=s1+"ddd";
friend CString operator+(const char *s,const CString &sa);
friend ostream & operator<<(ostream &out,const CString &s);
private:
char *str;
int strlen(const char *s);
char *strcpy(char *strDest, const char *strSrc);
char *strcat(char *strDest, const char *strSrc);
};
int CString::strlen(const char *s)
{
int num=0;
if(s == NULL)
{
return num;
}
while( *s++ != '\0')// yhp\0
{
num++;
}
return num;
}
char * CString::strcat(char *strDest, const char *strSrc)
{
char * ret=strDest;
strDest+=strlen(strDest);
while((*strDest++ = *strSrc++) != '\0');
return ret;
}
char * CString::strcpy(char *strDest, const char *strSrc)
{
char *ret=strDest;
while((*strDest++ = *strSrc++) != '\0');
return ret;
/*
//char *ret=strDest;
int i=0;
for(i=0;strSrc[i] != '\0';i++)
{
strDest[i]=strSrc[i];
}
return strDest;
*/
}
CString::CString(int n)
{
if(n>1)
{
str=new char[n];
str[0]='\0';
}
else
{
str=new char[1];
str[0]='\0';
}
}
CString::CString(char *s)
{
if(s!=NULL)
{
str=new char[strlen(s)+1];
strcpy(str,s);
}
else
{
str=new char[1];
str[0]='\0';
}
}
CString::CString(const CString &s)
{
if(strlen(s.str)>1)
{
str=new char[strlen(s.str)+1];
strcpy(str,s.str);
}
else
{
str=new char[1];
str[0]='\0';
}
}
CString & CString::operator=(const CString &s)
{
if(this == &s)
return *this;
delete []str;// str=0;
str=new char[strlen(s.str)+1];
strcpy(str,s.str);
return *this;
}//s1.operator=(s2);
CString::~CString()
{
if(str != NULL)
{
delete []str;
}
str=NULL;
}
CString CString::operator+(const CString &sa)
{
char *s=new char[strlen(this->str)+strlen(sa.str)+1];
strcpy(s,this->str);
strcat(s,sa.str);
return CString(s);
}
void main()
{
CString s1;
CString s2("ym");
CString s3;
s3=s1+s2;
s3=s1+"dddddd";
s3="ddddd"+s1;// operator+("ddddd",s1);
}
/* //char *p="yhphm";//*(p+0)
// cout<<(void *)p<<endl;//cout<<*p<<endl; cout<<p[0]<<endl;
char p[]={"yhphm"};
cout<<p<<endl;
cout<<*p<<endl;
cout<<&p<<endl;
cout<<(void *)p<<endl;
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -