1.4.4 Searching a String

Like other languages, C++ allows us to search a string for a value, however the syntax is a little different compared to languages like Java.

Find Command

In C++, you use the find command to search a string. If the string is found, the position where the first instance is found is returned.

When the string is not found, the string no position value is returned. This value is represented as string::npos.

Here is an example of the syntax to search for a cat.

string str = "alley cat";
if(str.find("cat") != string::npos) {
    cout << "I found a cat!" << endl;
}

Assigning a Value While Evaluating

One of the more unique features of C++ is that you can assign a value in the same statement that you evaluate it. This allows you to combine statements in a logical way. For example, if you wanted to find whether a phrase contained cat and print the position only if it does, you can do something like this:

int found;
if((found = str.find("cat")) != string::npos) {
    cout << "I found a cat at position ";
    cout << found << endl;
}

Notice that the variable was declared before the conditional statement and the variable assignment is in parenthesis so that it is created before evaluating.

Try This Example

Last updated