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')→2countOccurrences("Hello", 'h')→0(case-sensitive)
Example 1
Input
s (string) =
umbrellac (char) =
lReturns (int)
2Example 2
Input
s (string) =
successc (char) =
sReturns (int)
3Example 3
Input
s (string) =
educationc (char) =
uReturns (int)
1Example 4
Input
s (string) =
developerc (char) =
eReturns (int)
3To 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
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run