This post will discuss how to count occurrences of a char in a given string in C++.

1. Using std::string::find function

We can use std::string::find to search the string for the first occurrence of the specified character starting from the specified position in the string. It returns the position of the first occurrence of the specified character or string::npos if the character is not found.

Download  Run Code

Output:

Character + occurs 2 times

2. Using std::count function

We can simplify things using the standard algorithm std::count defined in the <algorithm> header. It returns the total number of elements that match the specified value in the given range.

Download  Run Code

Output:

Character + occurs 2 times

3. Using std::count_if function

Finally, we can also use std::count_if that uses a specified predicate for comparison, unlike std::count, which uses the == operator.

Download  Run Code

Output:

Character + occurs 2 times

4. Using Boost

If you don’t want to use the STL library, you can use boost’s count() function defined in the header file boost/range/algorithm/count.hpp.

Download Code

Output:

Character + occurs 2 times

That’s all about counting occurrences of a char in a string in C++.