In: Computer Science
Write a basic C++ program with function, whose input is a character and a string, and whose output indicates the number of times the character appears in the string.
Ex: If the input is:
n Monday
the output is:
1
Ex: If the input is:
z Today is Monday
the output is:
0
Ex: If the input is:
n It's a sunny day
the output is:
2
Case matters. n is different than N.
Ex: If the input is:
n Nobody
the output is:
0
Your program must define and call the following function that returns the number of times the input character appears in the input string.
int CountCharacters(char userChar, string userString)
266636.1461252
#include <iostream>
#include <string>
using namespace std;
int CountCharacters(char userChar, string
userString)
{
int count=0;
for (int i=0;i<userString.length();i++)
if (userString[i] == userChar)
count=count+1;
return count;
}
int main()
{
cout<<CountCharacters('n',"Monday")<<endl;
cout<<CountCharacters('z',"Today is
Monday")<<endl;
cout<<CountCharacters('n',"It's a sunny
day")<<endl;
cout<<CountCharacters('n',"Nobody")<<endl;
return 0;
}
Explanation :
1. we define a function CountCharacters which accepts 2 parameters char userChar and string userString.
2.We intialize variable count to 0 which will count the occurrence of the character userChar in the string userString.
3.We then define a for loop where i represents index of the string and we iterate through every character in string userString until index is less than length of userString that means we iterate until last character of the userString.
Example if userString = "Monday" then length of string =6 .
For loop will run until index<6 . Index always starts from 0
4.We check character at every index in string userString. and find if its equal to userChar . if its equal then we increment count by 1.
5.Finally the function return count when called in main function by passing the arguments.