#include <cstdlib>
#include <iostream>
#include "string.h"
using namespace std;
String::String(int length)
{
if ( length > 0 )
{
mString = new char[length+1]; mString[0] = '\0';
mRef = 1;
cout << "String(int) called, new string that is " << length << " char's long." << endl;
}
else
cout << "String::String(int length) -> ERROR! Bad length!" << endl << endl;
}
String::String(const char *str)
{
int maxlength = strlen(str)+1;
mString = new char[maxlength];
strncpy(mString,str,maxlength); mString[maxlength] = '\0';
mRef = 1;
cout << "String(char) called with new data as: " << this->GetString() << endl;
}
String::~String()
{
cout << "Destructor called on string with contents of: " << this->GetString() << endl;
KILL(mString);
}
String *String::DupString()
{
String *str = NULL; cout << "DupString called!" << endl;
str = new String(this->GetString());
if ( str != NULL )
return str;
else
return NULL;
}
bool String::Merge(String *str)
{
if ( str == NULL && str->Size() > 0)
return false;
cout << "Merge called between " << str->GetString() << " and " << this->GetString() << endl;
if ( !StrCmp( str->GetString(), this->GetString()) ) {
unsigned int oldref = this->GetRef();
for ( int i = 0; i < str->GetRef(); i++ ) this->AddRef();
if ( this->GetRef() > oldref ) {
str->Kill(); return true;
}
else
return false;
}
else
return false;
}
bool String::SetString(const char *str)
{
if ( mString != NULL )
KILL(mString);
int maxlength = strlen(str)+1;
mString = new char[maxlength];
strncpy(mString,str,maxlength); mString[maxlength] = '\0';
}
bool StrCmp( const char *astr, const char *bstr )
{
if ( !astr )
return true;
if ( !bstr )
return true;
for ( ; *astr || *bstr; astr++, bstr++ )
{
if ( tolower(*astr) != tolower(*bstr) )
return true; }
return false;
}