7.8. Our own version of find¶
If we are looking for a letter in a string, we may not want to
start at the beginning of the string. One way to generalize the find
function is to write a version that takes an additional parameter—the
index where we should start looking. Here is an implementation of this
function.
std::size_t find (string s, char c, std::size_t i) {
while (i < s.size()) {
if (s[i] == c) return i;
i = i + 1;
}
return std::string::npos;
}
Instead of invoking this function on a string, like the first
version of find, we have to pass the string as the first
argument. The other arguments are the character we are looking for and
the index where we should start. Both functions return
std::string::npos if there is no match. Our function also returns
std::string::npos if the starting index is at or beyond the size.
In the active code below, we are finding the index of the first 'e' character in
the "Shepard" part of "German Shepard" using our function.
Then we use the built-in find function to demonstrate how the starting index changes the result.
1#include <cstddef>
2#include <iostream>
3#include <string>
4
5using std::size_t;
6
7std::size_t find (std::string s, char c, std::size_t i) {
8 while (i < s.size()) {
9 if (s[i] == c) {
10 return i;
11 }
12 i = i + 1;
13 }
14 return std::string::npos;
15}
16
17int main() {
18 std::string dog = "German Shepard";
19 std::size_t start_shepard = 7;
20 std::cout << find(dog, 'e', start_shepard) << '\n';
21 std::cout << dog.find('e') << '\n';
22}
Q1
What is the correct output of the code below?
int main() {
string quote = "The way to get started is to quit talking and begin doing.";
cout << find(quote, 't', 11) << ", " << find(quote, 't', 42) << ", " << quote.find('t');
}