Count how many times a letter appears in a word.
What to build
A loop over the characters of a string.
Requirements
- Read a word and a letter.
- Print how many times the letter appears.
Input
One line: the word and then the letter.
Output
One number.
Constraints
The word has from 1 to 200 characters. Capital letters are different from small ones.
Example
Input:
banana a
Output:
3
Why it works
A range-based loop visits each character once, with no index to get wrong.
Examples
Example 1 · Input
banana a
Expected output
3
Example 2 · Input
sky z
Expected output
0
Hints
Hint 1
Use a range-based for loop over the string.
Hint 2
Read the letter into a char.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
using namespace std;
int main() {
string word;
char letter;
cin >> word >> letter;
int count = 0;
for (char c : word) {
if (c == letter) {
count++;
}
}
cout << count << endl;
return 0;
}