Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page