< Previous | Contents | Next >
Next I use the member function find() to check whether either of two string literals are contained in phrase. First, I check for the string literal "Over":
cout << "\nThe sequence ’Over’ begins at location "; cout << phrase.find("Over") << endl;
The find() member function searches the calling string object for the string supplied as an argument. The member function returns the position number of the first occurrence where the string object for which you are searching begins in the calling string object. This means that phrase.find("Over") returns the position number where the first occurrence of "Over" begins in phrase. Since phrase is "Lame Over!!!", find() returns 5. (Remember, position numbers begin at 0, so 5 means the sixth character.)
But what if the string for which you are searching doesn’t exist in the calling string? I tackle that situation next:
if (phrase.find("eggplant") == string::npos)
{
cout << "’eggplant’ is not in the phrase.\n\n";
}
Because "eggplant" does not exist in phrase, find() returns a special constant defined in the file string, which I access with string::npos. As a result, the screen displays the message, “’eggplant’ is not in the phrase.”
The constant I access through string::npos represents the largest possible size of a string object, so it is greater than any possible valid position number in a string object. Informally, it means “a position number that can’t exist.” It’s the perfect return value to indicate that one string couldn’t be found in another.
Hin t
When using find(), you can supply an optional argument that specifies a character number for the program to start looking for the substring. The following line will start looking for the string literal "eggplant" beginning at position 5 in the string object phrase.
location = phrase.find("eggplant", 5);