In: Computer Science
Write a program that accepts a string and character as input, then counts and displays the number of times that character appears (in upper- or lowercase) in the string. Use C++
Enter a string: mallet Enter a character: a "A" appears 1 time(s)
Enter a string: Racecar Enter a character: R "R" appears 2 time(s)
#include <iostream>
using namespace std;
int countChar(string s, char ch){
int count = 0;
for(int i = 0;i<s.length();i++){
if(s[i]>='a' && s[i]<='z'){
if((char)(s[i]-32)==ch){
count++;
}
}
else if(s[i]==ch){
count++;
}
}
return count;
}
int main()
{
string s;
char ch;
cout<<"Enter a string: ";
cin>>s;
cout<<"Enter a character: ";
cin>>ch;
if(ch>='a' && ch<='z'){
ch = ch - 32;
}
cout<<"\n\""<<ch<<"\" appears "<<countChar(s,ch)<<" time(s)"<<endl;
return 0;
}


