class String
{
public:
friend ostream& operator<<(ostream& os,const String&s)
{
os<<s._size<<" "<<s._capatity<<" "<<s._str<<endl;
return os;
}
String(const char*str="")
:_size(strlen(str)),
_capatity(_size),
_str(new char[strlen(str)+1])
{
strcpy(_str,str);
}
String(const String& s)
:_size(strlen(s._str)),
_capatity(s._size),
_str(new char[strlen(s._str)+1])
{
strcpy(_str,s._str);
}
String& operator=(const String&s)
{
if(this!=&s)
{
char* tmp=new char[strlen(s._str)+1];
delete[]_str;
strcpy(tmp,s._str);
_str=tmp;
_size=strlen(_str);
_capatity=strlen(_str);
}
return *this;
}
~String()
{
if(_str!=NULL)
{
delete[]_str;
_str=NULL;
}
}
char& operator[](size_t pos)
{
return _str[pos];
}
bool operator==(const String&s)const
{
int i=0;
for(i=0;i<_size&&i<s._size;i++)
{
if(_str[i]!=s._str[i])
{
return false;
}
}
if(i==_size&&i==s._size)
return true;
else
return false;
}
bool operator<(const String&s)const
{
int i=0;
for(i=0;i<_size&&i<s._size;i++)
{
if(_str[i]<s._str[i])
return true;
if(_str[i]>s._str[i])
return false;
}
if(i==_size&&i!=s._size)
return true;
else
return false;
}
bool operator !=(const String&s)const
{
return !(*this==s);
}
bool operator>(const String&s)const
{
return !(*this<s);
}
bool operator<=(const String&s)const
{
return (*this<s)||(*this==s);
}
bool operator>=(const String&s)const
{
return (*this>s)||(*this==s);
}
void Expand(size_t n)
{
if(n>_capatity)
{
_str=(char*)realloc(_str,n+1);
assert(_str);
_capatity=n;
}
}
void Pushback(char ch)
{
if(_size=_capatity)
{
Expand(_capatity*2);
}
_str[_size++]=ch;
_str[_size]='\0';
}
void Pushback( char* str)
{
size_t len=strlen(str);
if(_size+len>_capatity)
{
Expand(_size+len);
}
strcpy(_str+_size,str);
_size+=len;
}
void Popback()
{
assert(_str);
_str[--_size]='\0';
}
void Insert(size_t pos,char ch)
{
assert(_str);
size_t end=_size;
while(pos<=end)
{
_str[end+1]=_str[end];
--end;
}
_str[pos]=ch;
_size++;
}
void Insert(size_t pos,char* str)
{
assert(_str);
size_t len=strlen(str);
if(_size+len>_capatity)
{
Expand(_size+len);
}
int end=_size;
while(pos<=end)
{
_str[end+len]=_str[end];
--end;
}
while(*str)
{
_str[pos++]=*str++;
}
_size+=len;
}
void Erase(size_t pos,size_t len)
{
assert(_str);
if(pos+len>_size)
{
_str[pos]='\0';
_size=pos;
}
else
{
strcpy(_str+pos,_str+pos+len);
_size-=len;
}
}
int Find(char ch)
{
int i=0;
int pos=0;
size_t len=strlen(_str);
for(i=0;i<len;i++)
{
if(_str[i]==ch)
return pos;
pos++;
}
/*while(*_str++)
{
if(*_str==ch)
{
return pos;
}
pos++;
}*/
return -1;
}
String类的增删查改
最新推荐文章于 2023-07-22 17:24:10 发布