EasyFoundational
Count Occurrences of a Character
- Time limit
- 1 s
- Memory limit
- 128 MB
- Estimated
- 15 min
Description
Given a string s and a single character ch, return the number of times ch occurs in s.
The comparison is case-sensitive. For example, a and A are different characters. If ch does not occur in the string, return 0. If the input string is empty, the result is also 0.
The character ch is guaranteed to contain exactly one character. The string may contain letters, digits, spaces, or punctuation.
Examples:
s = "banana", ch = "a"returns3.s = "Hello", ch = "l"returns2.s = "Hello", ch = "h"returns0.
Implement countOccurrences(s, ch).
Constraints
0 <= s.length <= 100000 ch.length = 1 s and ch contain standard ASCII characters.
Sample cases
3Sample 1
Input
s = "banana" ch = "a"
Expected output
3
Sample 2
Input
s = "Hello" ch = "l"
Expected output
2
Skills and languages
Patterns
- Frequency Counting
Languages
- Python 3
Solve this problem
Create a free account to write, run and submit your solution.
- Write Python or Java in the browser, with your draft saved as you type
- Run your code on the examples as often as you like
- Submit to a sandboxed judge and see exactly which case failed
- Ask the AI mentor for a hint without being handed the answer