Answer:
#include<iostream>
using namespace std;
int CountCharacters(char userChar, const string inputstr){
int k = 0;
int iter = 0;
for (iter = 0; iter < inputstr.size(); iter++){
if (inputstr[iter] == userChar){
++k; }}
return k;}
int main(){
string str;
char userChar[1];
cout<<"Char: "; cin>>userChar;
cin.ignore();
cout<<"String: "; getline(cin, str);
cout<<CountCharacters(userChar[0],str);
return 0;}
Explanation:
Written in C++:
The function is defined here:
int CountCharacters(char userChar, const string inputstr){
This initializes a count variable k to 0
int k = 0;
This initializes an iterating variable iter to 0
int iter = 0;
This iterates through the characters of the string being passed to the function
for (iter = 0; iter < inputstr.size(); iter++){
This checks for matching characters
if (inputstr[iter] == userChar){
If found, k is incremented by 1
++k; }}
This returns the total count
return k;}
The main begins here
int main(){
This declares a string variable
string str;
This declares a character variable
char userChar[1];
This gets input for the character variable
cout<<"Char: "; cin>>userChar;
This lets the user get another input
cin.ignore();
This gets input for the string variable
cout<<"String: "; getline(cin, str);
This calls the function and return the count of character in the string
cout<<CountCharacters(userChar[0],str);