//-------------------------------------------------------------------- // // Laboratory 3 stradt.cpp // // SOLUTION: Array implementation of the String ADT // //-------------------------------------------------------------------- #include #include #include #include #include "stradt.h" //-------------------------------------------------------------------- stradt:: stradt ( int numChars ) // Creates an empty string. Allocates enough memory for numChars+1 // characters (defaults to 1 character). : bufferSize(numChars+1) { buffer = new char [ bufferSize ]; // Allocate memory for buffer assert ( buffer != 0 ); // Confirm allocation buffer[0] = '\0'; // Set string to empty } //-------------------------------------------------------------------- stradt:: stradt ( const char *charSeq ) // Creates a string containing the delimited sequence of characters // charSeq. Allocates enough memory for this string. { bufferSize = strlen(charSeq) + 1; // Account for null buffer = new char [ bufferSize ]; // Allocate memory assert ( buffer != 0 ); strcpy(buffer,charSeq); // Copy the string } //-------------------------------------------------------------------- stradt:: ~stradt () // Frees the memory used by a string. { delete [] buffer; } //-------------------------------------------------------------------- int stradt:: length () const // Returns the number of characters in a string (excluding the // null character). { return strlen(buffer); } //-------------------------------------------------------------------- char stradt:: operator [] ( int n ) const // Returns the nth character in a string -- where the characters are // numbered beginning with zero. { if ( n >= 0 && n <= length() ) return buffer[n]; else return '\0'; } //-------------------------------------------------------------------- void stradt:: operator = ( const stradt &rightString ) // Assigns rightString to a string. { int rlen = rightString.length(); // Length of rightString if ( rlen >= bufferSize ) // If rightString will not fit { delete [] buffer; // Release buffer and bufferSize = rlen + 1; // allocate a new buffer = new char [ bufferSize ]; // (larger) buffer assert ( buffer != 0 ); } strcpy(buffer,rightString.buffer); // Copy rightString } //-------------------------------------------------------------------- void stradt:: clear () // Clears a string -- i.e., makes it empty. The buffer size // remains unchanged. { buffer[0] ='\0'; } //-------------------------------------------------------------------- void stradt:: showStructure () const // Outputs the characters in a string. This operation is intended for // testing/debugging purposes only. { int j; // Loop counter for ( j = 0 ; j < bufferSize ; j++ ) cout << j << "\t"; cout << endl; for ( j = 0 ; buffer[j] != '\0' ; j++ ) cout << buffer[j] << "\t"; cout << "\\0" << endl; }