// Implementation for a simple String class // The MyString object has data storage for the characters of the // string as well as recording the length of the string. The storage // is done as a C style string, with a terminating null byte, so we // must be careful to always allocate enough storage. #include "MyString.h" #include "string.h" // Constructors // Empty String or c style string MyString::MyString(const char * cstring) : len(::strlen(cstring)) { sdata = new char[len + 1]; ::strcpy(sdata, cstring); } // Copy constructor MyString::MyString(const MyString & s) : len(s.length()) { sdata = new char[len + 1]; ::strcpy(sdata, s.sdata); } // Private constructor for pre-allocation MyString::MyString(const char * cs, unsigned int alloclen) { sdata = new char[alloclen + 1]; ::strncpy(sdata, cs, alloclen); sdata[alloclen] = '\0'; len = ::strlen(sdata); // The actual length } // Assignment between various forms of Strings MyString & MyString::operator = (const MyString & rhs) { // Check for self assignment if (this != &rhs) *this = rhs.sdata; return *this; } MyString & MyString::operator = (const char * cstring) { len = ::strlen(cstring); char * nsdata = new char[len + 1]; ::strcpy(nsdata, cstring); delete sdata; sdata = nsdata; return *this; } // Character access char & MyString::operator [] (int i) { // Return a valid reference even if out of range if (i < 0 || i >= len) { static char junk = '\0'; return junk; } else return sdata[i]; } // Concatenation MyString MyString::operator + (const MyString & toAppend) const { // Allocate for concatenated size unsigned int nlen = len + toAppend.length(); MyString result(sdata, nlen + 1); ::strcat(result.sdata, toAppend.sdata); result.len = nlen; return result; }