Searching in a String
The method find() searches a string for a shorter string or a character, and returns the index where it first occurs:
std::string message = "the troll hits the hero";
std::cout << message.find("troll") << std::endl;
std::cout << message.find('h') << std::endl;
std::cout << message.find("the", 1) << std::endl;
std::cout << message.find("dragon") << std::endl;This prints:
4
1
15
4294967295The word troll starts at index 4, and the first h is at index 1. With a second number, find() starts searching at that index: find("the", 1) skips the the at index 0 and finds the next one, at index 15.
There's no dragon in the message. When find() finds nothing, it returns std::string::npos (no position), a special value bigger than any index. Here it's 4294967295, and on your computer it may be another, even bigger number. You don't need to remember it, just compare with std::string::npos:
if (message.find("dragon") == std::string::npos) {
std::cout << "No dragon here" << std::endl;
}
int position = message.find("hero");
if (position != std::string::npos) {
std::cout << "Hero at " << position << std::endl;
}This prints:
No dragon here
Hero at 19As the example shows, you can store the index in an int. When nothing is found, the int holds -1, but the comparison with std::string::npos still works.
Watch out: find() returns an index, not a yes or a no. This condition compiles, but it's wrong:
if (message.find("the")) {
std::cout << "Found it" << std::endl;
} else {
std::cout << "Not found" << std::endl;
}It prints Not found, because the is at index 0, and 0 counts as false. And when a word isn't in the message at all, the condition is true, because npos isn't 0. So always compare with std::string::npos.
To find every occurrence, search again in a loop, each time from the index after the last one found, until find() returns npos:
int position = message.find('h');
while (position != std::string::npos) {
std::cout << "h at " << position << std::endl;
position = message.find('h', position + 1);
}This prints:
h at 1
h at 10
h at 16
h at 19Instructions
- 1
Find out where the dragon is. When the row has a
D, print its index:Dragon at 9. When it hasn't, printNo dragon. The test also runs your program with other rows, with and without a dragon. - 2
Below that, print the index of every coin, each on its own line:
Coin at 5,Coin at 12andCoin at 17. Look for the coins withfind()in awhileloop, as in the last example.