Given a string s
and a letter c. Determine how many times the letter c appears in
the string s.
Input. The first line
contains the string s, with a length not exceeding 100 characters. The
second line contains a lowercase letter c from the Latin alphabet.
Output. Print the number of
occurrences of the letter c in the string s, case-insensitively.
For example, the letters ‘a’ and ‘A’ are considered the same.
Sample input 1 |
Sample output 1 |
Programming
Principles 1 P |
3 |
|
|
Sample input 2 |
Sample output 2 |
This is a cat sitting
on a table t |
5 |
strings
Algorithm
analysis
The task
is to count how many times the letter c appears in the string s.
Uppercase and lowercase letters are considered identical.
Algorithm implementation
Read the input string s and the character ch.
getline(cin,
s);
cin >> ch;
Count the occurrences of the letter ch in the
string s. Convert each character s[i] to lowercase and compare it with ch, which is given in lowercase.
cnt = 0;
for (i = 0; i < s.length(); i++)
if (tolower(s[i]) == ch) cnt++;
Print the answer.
cout << cnt;
Python implementation
Read the input string s and the character ch.
s = input()
ch = input()
Convert the string s
to lowercase. This ensures that the character count is case-insensitive,
meaning ‘A’ and ‘a’ are treated as the same character. Then, store in
the variable res the number of occurrences of the character ch in
the string s after it is converted to lowercase.
res = s.lower().count(ch)
Print the answer.
print(res)