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)
Example 1
Input:
s (string) = umbrella
c (char) = l
Return:
(int) 2
Example 2
Input:
s (string) = success
c (char) = s
Return:
(int) 3
Example 3
Input:
s (string) = education
c (char) = u
Return:
(int) 1
Example 4
Input:
s (string) = developer
c (char) = e
Return:
(int) 3

To count character occurrences:

  1. Initialize a counter to 0.
  2. Loop through each character in the string.
  3. If the current character equals the target character, increment the counter.
  4. 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
Run your code to see the result.