Search

In this lesson, we'll examine the different search features available in the string class.

C++ offers the ability to search in a string in many variations. Each variation exists in various overloaded forms.

ℹ️ Search is called find
Odd enough the algorithms for search in a string starts with the name find. If the search was successful, you get the index of type std::string::size_type, if not, you get the constant std::string::npos. The first character has an index of 0.

The find algorithms support to:

  • search for a character, a C String or a C++ string,
  • search for a character from a C or C++ string,
  • search forward and backward,
  • search positive (does contain) or negative(does not contain) for characters from a C or C++ string,
  • start the search at an arbitrary position in the string.

The arguments of all six variations of the find functions follow a similar pattern. The first argument is the text you are searching for. The second argument holds the start position of the search and the third the number of characters starting from the second argument.

Here are the six variations.

Methods Description
str.find(...) Returns the first position of a character, a C or C++ string in str.
str.rfind(...) Returns the last position of a character, a C or C++ string in str.
str.find_first_of(...) Returns the first position of a character from a C or C++ string in str.
str.find_last_of(...) Returns the last position of a character from a C or C++ string in str.
str.find_first_not_of(...) Returns the first position of a character in str, which is not from a C or C+±string.
str.find_last_not_of(...) Returns the last position of a character in str, which is not from a C or C+±string.

Find variations of the string

Get hands-on with 1000+ tech skills courses.