/****************************************************************************************************************
* string class. 仿真std::string
* SDU. All Rights Reserved.
* Author: Guangcong Liu
****************************************************************************************************************
*/
#include <cstddef>
#include <cassert>
#include <cstring>
class string;
string operator+(const string&, const string&);
bool operator==(const string&, const string&);
class string{
public:
string(const char* = 0);
string(const string&);
~string();
string& operator=(const string&);
string& operator=(const char*);
string& operator+=(const string&);
string& operator+=(const char*);
size_t size() const;
char& operator[](size_t);
const char& operator[](size_t) const;
const char* c_str() const;
private:
char* _str;
};
string::string(const char* str)
{
if(str == 0)
{
_str = new char[1];
_str[1] = '/0';
}
else
{
_str = new char[strlen(str) + 1];
strcpy(_str, str);
}
}
string::string(const string& other)
{
_str = new char[strlen(other._str) + 1];
strcpy(_str, other._str);
}
string::~string()
{
delete [] _str;
}
string& string::operator=(const string& rhs)
{
if(&rhs != this)
{
delete [] _str;
_str = new char[strlen(rhs._str) + 1];
strcpy(_str, rhs._str);
}
return *this;
}
string& string::operator=(const char* rhs)
{
if(rhs != _str)
{
delete [] _str;
_str = new char[strlen(rhs) + 1];
strcpy(_str, rhs);
}
return *this;
}
string& string::operator+=(const string& rhs)
{
char * ori = _str;
_str = new char[strlen(ori) + strlen(rhs._str) + 1];
strcpy(_str, ori);
strcat(_str, rhs._str);
delete [] ori;
return *this;
}
string& string::operator+=(const char* rhs)
{
if(rhs)
{
char * ori = _str;
_str = new char[strlen(ori) + strlen(rhs) + 1];
strcpy(_str, ori);
strcat(_str, rhs);
delete [] ori;
}
return *this;
}
string operator+(const string& lhs, const string& rhs)
{
string temp = lhs;
temp += rhs;
return temp;
}
bool operator==(const string& lhs, const string& rhs)
{
if(strcmp(lhs.c_str(), rhs.c_str()) == 0) return true;
return false;
}
size_t string::size() const
{
return strlen(_str);
}
char& string::operator[](size_t i)
{
return _str[i];
}
const char& string::operator[](size_t i) const
{
return _str[i];
}
const char* string::c_str() const
{
return _str;
}