7.7. The find function

The string class provides several other functions that you can invoke on strings. The find function is like the opposite the [] operator. Instead of taking an index and extracting the character at that index, find takes a character and finds the index where that character appears.

Take a look at the active code below, which uses the find function to find the character 'a' in string fruit and string dessert.

This example finds the index of the letter 'a' in the string. In this case, the letter appears three times, so it is not obvious what find should do. According to the documentation, it returns the index of the first appearance, so the result is 1. If the given letter does not appear in the string, find returns -1.

In addition, there is a version of find that takes another string as an argument and that finds the index where the substring appears in the string.

The active code below finds the starting index of "nan" in fruit.

This example returns the value 2.

You should remember from Section 5.4 that there can be more than one function with the same name, as long as they take a different number of parameters or different types. In this case, C++ knows which version of find to invoke by looking at the type of the argument we provide.

Construct a block of code that correctly finds and prints where the first “B” is in the string. Declare city before index.

You have attempted of activities on this page