Count occurrences of a char in a string in C++
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <string> int main() { std::string s = "C++,Java"; char ch = '+'; int count = 0; for (int i = 0; (i = s.find(ch, i)) != std::string::npos; i++) { count++; } std::cout << "Character " << ch << " occurs " << count << " times"; return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <algorithm> #include <string> int main() { std::string s = "C++,Java"; char ch = '+'; int count = std::count(s.begin(), s.end(), ch); std::cout << "Character " << ch << " occurs " << count << " times"; return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <algorithm> #include <string> int main() { std::string s = "C++,Java"; char ch = '+'; int count = std::count_if (s.begin(), s.end(), [&ch](char c) { return c == ch; }); std::cout << "Character " << ch << " occurs " << count << " times"; return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <string> #include <boost/range/algorithm/count.hpp> int main() { std::string s = "C++,Java"; char ch = '+'; int count = boost::count(s, ch); std::cout << "Character " << ch << " occurs " << count << " times"; return 0; } |
Output:
Character + occurs 2 times
That’s all about counting occurrences of a char in a string in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)