find occurrence of character in string c++ code example

Example 1: find all occurrences of a substring in a string c++

#include <string>
#include <iostream>

using namespace std;

int main()
{
    string s("hello hello");
    int count = 0;
    size_t nPos = s.find("hello", 0); // first occurrence
    while(nPos != string::npos)
    {
        count++;
        nPos = s.find("hello", nPos + 1);
    }

    cout << count;
};

Example 2: count occurrences of character in string c++

std::string s = "a_b_c";
size_t n = std::count(s.begin(), s.end(), '_'); // n=2

Example 3: find last occurrence of character in string c++

auto find_char = 'a'
size_t last_occurence_index = str.find_last_of(find_char);

Tags:

Cpp Example