/* Questions to ask: 1) Difference between c strings and strings? - We know the length of string - String has functions built in */ #include "string.h" #include using namespace std; String::String() { init(DEFAULT_SIZE,""); } String::String(int size) { init(size,""); } String::String(char* initString) { init(DEFAULT_SIZE, initString); } String::String(int size, char* initString) { init(size,initString); } void String::init(int initCapacity, char* initString) { stringLength = strlen(initString); // Get the length of the c_string arrayLength = max(initCapacity,stringLength); // Array length is max str = new char[arrayLength]; // dynamically create array strcpy(str,initString); // copy contents of initString } const char* String::c_str() const { return str; } char& String::at ( int pos ) { return str[pos]; } int String::capacity ( ) const { return arrayLength; } int String::size ( ) const { return stringLength; } void String::clear() { at(0) = '\0'; stringLength = 0; } int String::compare ( const String& str ) const { return strcmp(this->str,str.c_str()); } String& String::append(const string& str) { int finalSize = strlen(str) + stringLength + 1; if(finalSize > arrayLength) { // if we dont have enough room char* tmp = new char[finalSize]; // create new array this->arrayLength = finalSize; // We have a new array length strcpy(tmp, this->str); // copy into tmp strcat(tmp, str); // concatenate into tmp delete this->str; // delete old memory this->str = tmp; // copy the ptr from tmp to class var } else { strcat(this->str, str); // we have enough memory so just simple strcat } this->stringLength = finalSize; // we have a new stringLength! return this; } // This is operator overloading so we can cout this class. You can look // forward to learning this soon! ostream& operator << (ostream& os, const String& s) { return os << s.c_str(); } int main() { String s("Hello"); cout << s.c_str() << endl; s.at(1) = 'a'; cout << s.c_str() << endl; cout << s.compare(s) << endl; String s2(" World"); cout << s.append(s2) << endl; cout << s << endl; }