#include #include #include #include using namespace std; class String { public: String( ) : strLen( 0 ), bufferLen( 1 ) { buffer = new char[ 1 ]; buffer[ 0 ] = '\0'; } String( const char *str ) { if( str == NULL ) str = ""; strLen = strlen( str ); bufferLen = strLen + 1; buffer = new char[ bufferLen ]; strcpy( buffer, str ); } String( const String & other ) { strLen = other.strLen; bufferLen = strLen + 1; buffer = new char[ bufferLen ]; strcpy( buffer, other.buffer ); } ~String( ) { delete [ ] buffer; } String operator+( const String & rhs ) const { String result = (*this); result += rhs; return result; } const String & operator+= ( const String & rhs ) { if( this == &rhs ) { String copy( rhs ); return *this += copy; } int newLength = length( ) + rhs.length( ); if( newLength >= bufferLen ) { bufferLen = 2 * ( newLength + 1 ); char *oldBuffer = buffer; buffer = new char[ bufferLen ]; strcpy( buffer, oldBuffer ); delete [ ] oldBuffer; } strcpy( buffer + length( ), rhs.buffer ); strLen = newLength; return *this; } const String & operator= ( const String & rhs ) { if( this != &rhs ) { if( bufferLen < rhs.length( ) + 1 ) { delete [ ] buffer; bufferLen = rhs.length( ) + 1; buffer = new char[ bufferLen ]; } strLen = rhs.strLen; strcpy( buffer, rhs.buffer ); } return *this; } int length( ) const { return strLen; } const char * c_str( ) const { return buffer; } char operator[]( int idx ) const { return buffer[ idx ]; } char & operator[]( int idx ) { return buffer[ idx ]; } bool operator==( const String & rhs ) const { return strcmp( buffer, rhs.buffer ) == 0; } bool operator==( const char *rhs ) const { return strcmp( buffer, rhs ) == 0; } private: char *buffer; // storage for characters int bufferLen; // size of the buffer int strLen; // length of string < bufferLen }; ostream & operator<< ( ostream & out, const String & x ) { out << x.c_str( ); return out; } bool operator==( const char *lhs, const String & rhs ) { return strcmp( lhs, rhs.c_str( ) ) == 0; } bool operator!=( const String & lhs, const String & rhs ) { return strcmp( lhs.c_str( ), rhs.c_str( ) ) != 0; } int main( ) { const String s1 = "hello"; String s2 = "world"; String s3 = s1; cout << s1.length( ) << endl; cout << s1 << endl; cout << s2 << endl; cout << s3 << endl; cout << (s1==s2) << endl; cout << (s1!=s3) << endl; cout << (s1=="world") << endl; cout << ("world"==s1) << endl; for( int i = 0; i < s1.length( ); i++ ) cout << s1[ i ] << endl; s3[ 0 ] = 'j'; cout << s3 << endl; s3 += s2; cout << s3 << endl; return 0; }