VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-count-occurrence-given-character-string/

⇱ Count Occurrences of a Given Character in a String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Occurrences of a Given Character in a String

Last Updated : 10 Apr, 2025

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

Examples: 

Input : S = "geeksforgeeks" and c = 'e'
Output : 4
Explanation: 'e' appears four times in str.

Input : S = "abccdefgaa" and c = 'a'
Output : 3
Explanation: 'a' appears three times in str.

Linear Search

Iterate through the string and for each iteration, check if the current character is equal to the given character c. If equal, then increments the count variable which stores count of the occurrences of the given character c in the string.


Output
4

Time Complexity:O(n), where n is the size of the string given.
Auxiliary Space: O(1)

Using Inbuilt Functions

The idea is to use inbuilt method in different programming languages which returns the count of occurrences of a character in a string.


Output
4

Time Complexity: O(n), where n is the size of the string given.
Auxiliary Space: O(1) 

Using Recursion - Not Efficient (Only for Learning Purpose)

This approach uses recursion to count the occurrences of a given character in a string. Checks if the character at the current index matches the target character, increments the count if it does, and then makes a recursive call to check the remaining part of the string. The process continues until the end of the string is reached, and the accumulated count would be the result.


Output
4

Time Complexity: O(n), where n is the size of string given.
Auxiliary Space: O(n), due to the recursion stack, where n is the size of string.

Comment
Article Tags:
Article Tags: