Implement the method countOccurrences
that takes a string and a character as input and returns the number of times that character appears in the string.
Learner Level
Loop
Write a function that counts how many times a specific character appears in a given string. The comparison should be case-sensitive, meaning
'A'
and 'a'
are treated as different characters.
Example:
countOccurrences("hello", 'l')
→2
countOccurrences("Hello", 'h')
→0
(case-sensitive)
To count character occurrences:
- Initialize a counter to 0.
- Loop through each character in the string.
- If the current character equals the target character, increment the counter.
- Return the final count.
Pseudocode:
Function countOccurrences(s, ch):
count ← 0
For each character c in s:
If c equals ch:
count ← count + 1
Return count