Lesson 24 - apstring class

INTRODUCTION:               Strings are needed in many large programming tasks.  Much of the information which identifies a person must be stored as a string:  name, address, city, social security number, etc. 

A standard apstring class has been provided for your use.  Your job in this lesson is to learn the specifications of the apstring class and use it to solve string-processing questions.

The key topics for this lesson are:

A.  C-style Strings

B.   The apstring Constructors

C.  String Assignment Operations

D.  String Accessor Functions

E.   String Indexing

F.   String Modifiers and Concatenations

G.  String Input/Output Operators

H.  String Relational Operators

VOCABULARY:                   none                                        

DISCUSSION:                       A.  C-style Strings

1.   A string is defined as a collection of characters with a special terminating character at the end of the string.  Strings are different from character variables in that strings can hold more than one character at a time.  Here are some examples of strings:




2.   The apstring class has been coded using a C-style string as a private data member.  A string in C is implemented as an array of char, terminated with the null character, '\0'  (that's a zero).

3.   So the C-style string to store our favorite C++ output, "hello world" is actually stored as:

      "hello world\0"

4.   The apstring class will use a mixture of C++ code and C routines to implement the string abstraction.  However, do not worry about the C programming tools used in the apstring class.  The only C programming syntax you need to know about strings is that they end with '\0'.

5.   The rest of the student outline parallels the list of constructors, member functions, and non-member free functions given in Handout H.A.24.1, apstring Class.  Assume that the identifiers word1, word2, and word3 are all of type apstring.

B.   The apstring Constructors

1.   There are 3 constructors in the apstring class:


Sample syntax






apstring word1;  // word1 is an empty string


apstring (const char *s = 0);


apstring word1 ("Hello world\0");

   // construct and copy a C-style string


apstring (const apstring &x);


apstring word2 (word1);  // copy constructor


C.  String Assignment Operations

1.   The apstring class has been overloaded to support three different assignment operations.

Assignment Operator

Sample syntax



const  apstring & operator = (const apstring  &str);



word2 = word1;


const  apstring & operator = (const char *s);


word1 = "Hello world\0";



const  apstring & operator = (char ch);


word1 = 't';


2.   As expected for an assignment operator, these three overloaded versions of the assignment operator return the value assigned.  For example, in the statement  word2 = word1, this expression returns the value of word1.  The allows for chaining of statements like

      word3 = word2 = word1;

D.  String Accessor Functions

1.   There are five accessor functions in the apstring class.  Notice that all five are const member functions.  The apstring object is protected from any changes when the object is inspected.

Accessor function

Sample syntax



int  length() const;



int  len = word1.length();


int  find (const apstring &str) const;


int  n = word1.find(word2);



int find (char ch) const;


int  n = word1.find('t');



apstring substr (int pos, int len) const;


word2 = word1.substr (1,3);

   // returns an apstring 3 characters long

   // starting at pos 1 of word1


const char* c_str () const;


char * cstring = word1.c_str();


2.   The function   int find (const apstring &str)  will find the first occurrence of str  within this apstring and return the index of the first character.  If str  does not occur in this apstring, the function returns npos.  The value npos is a const value defined in the apstring class and can be used in your programs.  Use the identifier  npos  and not the value -1 as assigned in the apstring.cpp implementation.

3.   The function  int find (char ch)  is identical in function and output to the other find function except it is looking for a single character.

4.   Here is a more complete example of using  substr:

        word1 = "San Jose, California\0";

        small = word1.substr(4,8);

        cout << small << endl;

   Run output:  Jose, Ca

      It is important to remember that strings are stored from position 0..length-1 of an array.  In the example above, word1[4] is the 5th character in the string.

5.   The  const char* c_str() const   function allows you to convert an apstring to a C-style string.  Here is an example:

void demo (const apstring &w1)


        char *cstring;

        cstring = w1.c_str();

        puts (cstring);              // tool in stdio.h to output a char* C-style string


6.   Converting apstrings to c-style strings is useful in opening a text file for processing.   For example:

void  demoFiles (apstring fileName)


        char  *fn = fileName.c_str();      // converts fileName to c-style string

        ifstream  inFile;    // use fn to open and link inFile


        if (inFile.fail())


                cerr << "Could not open " << fileName << endl;




                // ... rest of code ...


E.   String Indexing

1.   Because apstrings are implemented as arrays of characters, it is possible to manipulate strings using the [] indexing operator.  The following code is legal:

        int  len = word1.length();

        for (int k=0; k < len; k++)

                cout << word1[k];

      This will print out the string.

2.   It is also possible to change the contents of a string using the index operator.  The following code will convert any lower case letters in a string into upper case letters.

int  len = word1.length();

for (int k=0; k < len; k++)

        if (('a' <= word1[k]) && (word1[k] <= 'z'))

                word1[k] -= 32;   

F.   String Modifiers and Concatenations

1.   The += operator has been overloaded to work with strings.  The following statements are possible.

        word1 += word2;           // this appends word2 to the end of word1

        word1 += 's';   // this appends an 's' to the end of word1

2.   You can also write similar statements using the + and = operator.  The following statements are legal using the apstring class.

word1 = word1 + word2;  // this has the same effect as word1 += word2;

word2 = word1 + 's';           // you can add a char to a string

word2 = 's' + word1;           // or vice versa

G.  String Input/Output Operators

1.   The output operator (<<) has been overloaded to work with apstrings. 

        cout << word1 << endl;              // sends word1 to cout

2.   The input operator (>>) has also been overloaded to support input of strings, but it has limitations.  It redirects input to a string until a whitespace character is encountered (tab, space bar, return key).  For example:

        cout << "Enter a string ---> ";

        cin >> word1;

        cout << endl << "word1 = " << word1 << endl;

   Run output:

   Enter a string ---> hello world

   word1 = hello

3.   In the above example, the attempt to enter the string as "hello world" was unsuccessful.  Only the word "hello" was accepted and stored in word1.

4.   An alternative tool to allow for input of a string with whitespace is getline.  Here is a sample usage of getline:

      getline (cin, word1);

        The string word1 is read from cin until a return key is hit.

H.  String Relational Operators

1.   Two strings can be compared using any of the standard relational operators:  ==, !=, <, >, <=, >=.

2.   Examples:

      word1 < word2

      word1 != word2

      word1 > "hello"

3.   A string can be compared to a C-style string.

SUMMARY/REVIEW:         The use of pre-existing code (classes) has helped reduce the time and cost of developing new programs.  In this lesson you will use the apstring class without knowing its inner details.  This is an excellent example of data type abstraction.

ASSIGNMENT:                    Lab Exercise, L.A.24-1, Strings