Program to count occurrence of a given character in a string
Examples:
Input : S = “CodeConfig” and c = ‘o’
Output : 2
Explanation: ‘o’ appears two times in str.Input : S = “abccdefgaa” and c = ‘a’
Output : 3
Explanation: ‘a’ appears three times in str.
Count occurrence of a given character in a string using simple Iteration:
Iterate through the string and when each iteration, check if the current character is equal to the given character c then increments the count variable which stores count of the occurrences of the given character c in the string.
Below is the implementation of above approach:
Python3
# Python program to count occurrences # of a given character # Method that return count of the # given character in the string def count(s, c) : # Count variable res = 0 for i in range ( len (s)) : # Checking character in string if (s[i] = = c): res = res + 1 return res # Driver code str = "CodeConfig" c = 'e' print (count( str , c)) |
4
Count occurrence of a given character in a string using Inbuild Functions:
The idea is to use inbuild functions/method in distinct programming languages which returns the count of occurrences of a character in a string.
Below is the implementation of above approach:
Python3
# Python program to count occurrences of # a character using library # Driver code to test above function str = "CodeConfig" c = 'e' # Count returns number of occurrences of # c between two given positions provided # when two iterators. print ( len ( str .split(c)) - 1 );
|
4
Count occurrence of a given character in a string using Recursion
Use a recursive approach 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.
Below is the implementation of above approach:
Python3
def count_in_string(ch, idx, s): # Base case: if the index reaches the end of the string, return 0 if idx = = len (s): return 0 count = 0 # Check if the current character of the string matches the given character if s[idx] = = ch: count + = 1 # Recursively count occurrences in the remaining part of the string count + = count_in_string(ch, idx + 1 , s) return count if __name__ = = "__main__" : str = "CodeConfig" c = 'e' print (count_in_string(c, 0 , str )) |
4