#include <iostream>
#include <cstring>
using namespace std;
class mystring;
class buf
{
char *stt;
int size;
public:
buf(const char *s)
{
size=strlen(s);
stt=new char[size+1];
strcpy(stt,s);
cout<<"有参构造"<<endl;
}
friend const bool &operator > (const mystring & s_1 ,const buf & s);
};
class mystring
{
private:
char *str;
int size;
public:
//无参构造
mystring():size(10)
{
str=new char[size];
cout<<"无参构造"<<endl;
}
//有参构造
mystring(const char *s)
{
size=strlen(s);
str=new char[size+1];
strcpy(str,s);
cout<<"有参构造"<<endl;
}
//拷贝构造
mystring(const mystring & other):str(new char(*(other.str))),size(other.size)
{
cout<<"拷贝构造"<<endl;
}
//拷贝赋值
mystring & operator=(const mystring &other)
{
if(this != &other)
{
*(this->str)=*(other.str);
this->size=other.size;
return *this;
}
}
//判空
int null(const char *s)
{
if(s==NULL)
return 0;
else
return 1;
}
//求字符串长度
ssize_t size_1()
{
return strlen(str);
}
//c_str函数
char *c_str()
{
return str;
}
//at函数
char &at(int pos)
{
if(pos>0&&pos<=size)
{
cout<<str[pos-1]<<endl;
}
return str[pos-1];
}
//为字符串赋值
mystring & operator=(const char *s)
{
strcpy(this->str,s);
return *this;
}
//访问指定字符
char & operator[](int num)
{
if(num<=0&&num>size)
{
cout<<"输入不合法,请输入小于"<<size<<"大于0的数"<<endl;
}
return str[num-1];
}
//字符串+=的运算
const mystring & operator +=(const char *s)
{
strcat(str,s);
size+=strlen(s);
return *this;
}
//两个字符串的+运算
const mystring & operator +(const char *s)
{
strcat(str,s);
size+=strlen(s);
return *this;
}
//字符串与一个字符的+运算
const mystring & operator +(const char s)
{
strcat(str,&s);
size+=1;
str[size]='\0';
return *this;
}
//遍历
void output()
{
cout<<"字符串="<<str<<endl;
}
//析构函数
~mystring()
{
delete str;
}
friend const bool & operator > (const mystring & s_1 ,const buf & s);
friend const ostream & operator <<(const ostream & L,const mystring & R);
friend const istream & operator >>(const istream & L,mystring & R);
};
//输出bool类型
const ostream & operator <<(const ostream & L,const bool & R)
{
cout<<R;
return L;
}
const bool &operator > (const mystring & s_1 ,const buf & s)
{
char *s1=s_1.str;
char *s2=s.stt;
if(strcmp(s1,s2)>0){
cout<<"ture"<<endl;
return true;
}
else{
cout<<"false"<<endl;
return false;
}
}
const ostream & operator <<(const ostream & L,const mystring & R)
{
cout<<"str="<<R.str<<"size="<<R.size<<endl;
return L;
}
const istream & operator >>(const istream & L,mystring & R)
{
cout<<"请输入字符串"<<endl;
cin>>R.str;
return L;
}
int main()
{
mystring s1("hello");
return 0;
}
2023/3/29 自主实现字符串的操作函数
于 2023-03-29 21:48:07 首次发布