Learner Level

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.

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
Returns (int) 2

Example 2

Input
s (string) = success
c (char) = s
Returns (int) 3

Example 3

Input
s (string) = education
c (char) = u
Returns (int) 1

Example 4

Input
s (string) = developer
c (char) = e
Returns (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
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.