Another way could be:
Given a string and a character, the task is to make a function that counts the occurrence of the given character in the string.
Examples:
Input : str = "endtoend"
c = 'e'
Output : 2
'e' appears four times in str.
Input : str = "abccdefgaa"
c = 'a'
Output : 3
'a' appears three times in str.
// C++ program to count occurrences of a given
// character
#include <iostream>
#include <string>
using namespace std;
// Function that return count of the given
// character in the string
int count(string s, char c)
{
// Count variable
int res = 0;
for (int i=0;i<s.length();i++)
// checking character in string
if (s[i] == c)
res++;
return res;
}
// Driver code
int main()
{
string str= "edureka";
char c = 'e';
cout << count(str, c) << endl;
return 0;
}
Output:
2 |