4.9. Finding Things in Strings
Problem
You want to search a string for something. Maybe it’s a single character, another string, or one of (or not of) an unordered set of characters. And, for your own reasons, you have to find it in a particular way, such as the first or last occurrence, or the first or last occurrence relative to a particular index.
Solution
Use one of basic_string’s “find” member functions.
Almost all start with the word “find,” and their name gives you a pretty good idea of what
they do. Example 4-15 shows how some of
the find member functions work.
Example 4-15. Searching strings
#include <string>
#include <iostream>
int main() {
std::string s = "Charles Darwin";
std::cout << s.find("ar") << '\n'; // Search from the
// beginning
std::cout << s.rfind("ar") << '\n'; // Search from the end
std::cout << s.find_first_of("swi") // Find the first of
<< '\n'; // any of these chars
std::cout << s.find_first_not_of("Charles") // Find the first
<< '\n'; // that's not in this
// set
std::cout << s.find_last_of("abg") << '\n'; // Find the first of
// any of these chars
// starting from the
// end
std::cout << s.find_last_not_of("aDinrw") // Find the first
<< '\n'; // that's not in this
// set, starting from
// the end
}Each of the find member functions is discussed in more detail in the “Discussion” section.
Discussion
There are six different find member functions for finding things in strings, each of
which provides four overloads. The overloads allow for either basic_string ...