Last Updated: 27 May, 2025

Count Character Occurrences

Easy

Problem statement

Given a string 'S' of length 'N' and a character 'C', the task is to count the occurrence of the given character in the string.


Return the total number of times the character 'C' appears in the string 'S'.


For Example :
Let 'N' = 5, 'S' = "bbacb", 'C' = 'b'.
The character 'b' appears 3 times in the string "bbacb".
Therefore, the answer is 3.
Input Format :
The first line contains the integer 'N', the length of the string 'S'.
The second line contains the string 'S' of length 'N'.
The third line contains the character 'C' to be counted.
Output Format :
Return the total count of the character 'C' in the string 'S'.
Note :
You don’t need to print anything. Just implement the given function.
Constraints :
1 <= 'N' <= 10^5
'a' <= characters in 'S' <= 'z'
'a' <= 'C' <= 'z'

Time Limit: 1 sec

Approaches

01 Approach

Approach:

  • Initialize a counter variable to zero.
  • Iterate through each character of the input string 'S'.
  • For each character in 'S', compare it with the given character 'C'.
  • If the characters match, increment the counter.
  • After iterating through the entire string, the value of the counter will be the total number of occurrences of 'C' in 'S'.

Algorithm:

  • Initialize a variable 'count' to 0.
  • Iterate using 'i' from 0 to 'N - 1':
    • If ( S[ i ] == C ):
      • Increment 'count' by 1.
  • Return 'count'.