Chapter 4 – The String ADT
In 1606, we dealt with “C strings”.
These were essentially character arrays with one little
twist – the use of a special terminator character to mark the end of data.
useful, especially given the collection of functions that allowed us to copy strings
(strcpy), compare strings (strcmp, stricmp), and perform a variety of other operations.
They were also far from ideal.
One problem was that, in declaring a string variable, we
had to pick some maximum size.
Another problem was that there was little protection
against strings “overflowing” and causing all kinds of problems. And, finally, strings
weren’t all that convenient to use.
Having to use “strcpy” to copy one string into another
wasn’t nearly as simple as copying, say, one double variable into another.
It would have
been much nicer to have been able to assign strings using the “=” operator (and to
compare them using “==”, “<”, and so on).
In C++, all these problems can (and have been) overcome.
The solution involves a
If one needs a string, one simply declares a “string” object.
There is no
need to specify a size.
Objects expand as required to accommodate the characters put
String objects may be manipulated in many ways. They may be read, written,
assigned, and compared (to name just the basics).
Moreover many of the operations are
implemented using “overloaded operators” (operators which have been given an
additional meaning beyond their default meaning).
To assign one string to another, for
example, one does not explicitly use a member function, but instead one uses the “=”
The net effect is that, from the user’s point of view, “string” looks much like a
built-in type (like double, int, and so on).
In order to use the “string” ADT, header file “string” must be included.
Note that there is
Header file “string.h” contains the prototypes for the various “C string”
functions (strcpy, strcmp, etc.) and this isn’t what we want.
It is also necessary to put
“using namespace std;” somewhere (the best spot is after all of the include’s but before
This is because, instead of being defined in the usual default
“namespace”, the “string” class is defined in a namespace called “std”.
Try thinking of
namespaces as dictionaries.
Normally all of the names we define (in creating variables
and so on) go into a default dictionary, and when names are used, the compiler refers to
this default dictionary to see what they mean.
The “string” class is not in this default
dictionary, but is instead in another dictionary called “std”.
If we simply use class
“string” in a program, the compiler will look for it in the default dictionary, find that it’s
not there, and give us an error message (even though “string” has been included).
make things work, we must tell the compiler that, as well as using the default dictionary,