// File: mystring.cpp // ================== // Implementation file for user-defined String class that stores // characters internally in a fixed size array. #include #include // for strlen(), etc. #include "mystring.h" String::String() { contents[0] = '\0'; len = 0; } void String::assign(const char s[]) { strcpy(contents, s); len = strlen(s); } void String::append(const String &str) { // Inefficient to use strcat() here since it will have to // search for the \0 character in 'contents' to find where // to append the additional characters. strcat(contents, str.contents); len += str.len; } int String::compare_to(const String &str) const { return strcmp(contents, str.contents); } void String::print() const { cout << contents; } int String::length() const { return len; } char String::element(int i) const { // cerr is like cout, but is where error messages should go. if (i < 0 || i >= len) { cerr << "can't access location " << i << " of string \"" << contents << "\"" << endl; return '\0'; } return contents[i]; }