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.
def main() {: string fruit = "apple"; int index_a = fruit.find('e'); int index_b = fruit.find("app"); int index_c = fruit.find('a'); int index_d = fruit.find('l'); }
Construct a block of code that correctly finds and prints where the first “B” is in the string. Declare city
before index
.
- Index to find sea is 29
find
returns the index of the FIRST occurence of "sea".- Index to find sea is 5
- Correct!
index
only has to look for a sequence arranged as "sea" in the string. - Index to find sea is -1
- sea is present in the
sentence
.
Q-5: What is printed when the code is run?
string sentence = "Most seas are rough but this sea is so calm!";
string target = "sea";
int index = sentence.find(target);
cout << "Index to find sea is " << index << endl;