(C++) Write a program whose input is two characters and a string, and whose output indicates the number of times each character appears in the string.
Ex: If the input is:
n M Monday
the output is:
1 1
Ex: If the input is:
z y Today is Monday
the output is:
0 2
Ex: If the input is:
n y It's a sunny day
the output is:
2 2
Case matters.
Ex: If the input is:
n N Nobody
the output is:
0 1
n is different than N.
#include <iostream> #include <string> using namespace std; int main() { char ch1, ch2; string str; int count1 = 0, count2 = 0, i; // initialize counts to 0 cin >> ch1 >> ch2; // read two characters getline(cin, str); // read rest of the line for (i = 0; i < str.size(); ++i) { // go through all characters of line if (str[i] == ch1) { // if character is same as the first character entered ++count1; // then increase count1 by 1 } if (str[i] == ch2) { // if character is same as the second character entered ++count2; // then increase count2 by 1 } } cout << count1 << " " << count2 << endl; // print counts return 0; }
Get Answers For Free
Most questions answered within 1 hours.