EECS 211
How to read Chapter 18

Chapter 18 is about C++ strings. Strings are used so frequently that a ton (metric weight) of functions and operators have been defined for them. Two good lists of the member functions and operators are:

You should not try to remember all of these. Instead, you should read through and see what they are and then, before writing any code to process a string, look again to see if a function already exists to do what you want. Don't reinvent the wheel.

Below are some non-obvious points about strings not made clear in Deitel.

What find returns for "not found"

There are a number of functions that search for substrings in strings, such as find(), find_first_of, find_last_of, and so on. When any of these functions fails to find what it's looking for, they return a special value. Deitel's example code suggests that this value is -1. It often is, but that's not portable. The actual value may not even be an integer. The guaranteed value is string::npos, which is of type string::size_type. Therefore, the correct way to check for "not found" is:

string s;
string::size_type pos;
pos = s.find("some substring");
if (pos == string::npos)

at() versus operator[]

The main difference is that at() should throw an out_of_range exception (which other code can catch) if you pass it a negative index or an index that's too large. operator[] does not do this. In general, this makes at() safer but possibly slower.


You have two different ways to compare strings. You can use the relational operators, ==, &, &=, and so on, just as you do with numbers. Or, you can use compare(string) which returns -1, 0, or 1, the way that the C library function strcmp() does.