/* string.cpp * A String ADT * Anthony Larrain * spring 2006 csc309 * * Note: print statements have been included in the constructors, the destructor * and assignment. */ #include #include #include #include #include using namespace std; class String { public: // Constructors String(const char *cstring = ""); // convert constructor String(char character); // convert constructor String(const String & str); // copy constructor //Destructor ~String(); //Assignment Operator const String & operator= (const String &rhs); // Transformers String & toLower(); String & toUpper(); // Other int size() const; // output string to the strean and newline void println(ostream &out) const; // output string - No newline void print(ostream &out) const; bool equals(const String & other) const; private: char *buffer; int len; }; String random() { srand(time(NULL)); static char vowel [] = {'a','e','i','o','u'}; static char novow [] = {'b','d','p','c','t'}; static char word [4]; word[0] = novow[rand() % 5]; word[1] = vowel[rand() % 5]; word[2] = novow[rand() % 5]; word[3] = '\0'; String str(word); return str; } int main() { String s1, // no arg constructor s2("Sunday"), // c-style string convert constructor s3(s2), // copy constructor s4('M'); // character convert constructor s1.println(cout); s2.println(cout); s3.println(cout); s4.println(cout); s2.toUpper(); s3.println(cout); s1 = s4; // calling assignment s1.println(cout); s1 = random(); // calling assignment and destructor s1.println(cout); char word[81]; cout << "Enter a word" << endl; cin >> word; String s5(word); cout << "You entered "; s5.println(cout); s5.toLower(); s5.println(cout); cout << "The number of characters is " << s5.size() << endl; cout << "Enter a sentence " << endl; // need to get rid of newline character. cin.ignore(2,'\n'); cin.getline(word, 81); s5 = word; // calling c-style convert and assignment String s6 = "SUNDAY"; s2.println(cout); s6.println(cout); if(s2.equals(s6)){ cout << "They are equal" << endl; }else{ cout << "Not equal" << endl; } system("pause"); return 0; } String::~String() { cout << "Calling Destructor" << endl; delete [] buffer; } String::String(const String & str) { cout << "Calling Copy" << endl; len = str.len; // one more for '\0' buffer = new char[len + 1]; strcpy(buffer, str.buffer); } String::String(const char *cstring) { cout << "Calling c-style string convert" << endl; if(cstring == NULL){ cstring = ""; } len = strlen(cstring); buffer = new char[len + 1]; strcpy(buffer, cstring); } String::String (char character) { len = 1; buffer = new char[len + 1]; buffer[0] = character; buffer[1] = '\0'; } const String & String::operator= (const String& rhs) { cout << "Calling Assignment " <