Finding characters in a string

suggest change

To find a character or another string, you can use std::string::find. It returns the position of the first character of the first match. If no match is found, the function returns std::string::npos.

// :glot
#include <iostream>
#include <string>

int main() {
    std::string str = "Curiosity killed the cat";
    auto pos = str.find("cat");

    if (pos != std::string::npos)
        std::cout << "Found at position: " << pos << '\n';
    else
        std::cout << "Not found!\n";
}
Found at position: 21

The search opportunities are further expanded by the following functions:

find_first_of     // Find first occurrence of characters 
find_first_not_of // Find first absence of characters 
find_last_of      // Find last occurrence of characters 
find_last_not_of  // Find last absence of characters

find_last_of and find_last_not_of search from the end of the string. find_first_not_of and find_last_not_of find a character that is not in the search string. Here is an example:

// :glot
#include <iostream>
#include <string>

int main() {
    std::string str = "dog dog cat cat";
    std::cout << "Found at position: " << str.find_last_of("gzx") << '\n';
}
Found at position: 6

Note: Be aware that the above functions do not search for substrings, but rather for characters contained in the search string. In this case, the last occurrence of 'g' was found at position 6 (the other characters weren’t found).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents