14: Count the occurrences of a character in a string.
⏳⌚ 00:00:00

Question:-

Count the occurrences of a character in a string.
Example 1:
Input:
s = "hello"
c = 'l'
Output: "2"
Example 2:
Input:
s = "geeksforgeeks"
c = 'e'
Output: "4"

Steps to solve:-

1. Count Function:- count is a user-defined function that takes two parameters: s (a string) and c (a character). It initializes an integer variable res to store the count of occurrences and sets it to 0. A for loop is used to iterate through the characters of the input string s. It starts from i = 0 and continues until i reaches the length of the string. Inside the loop, it checks if the character at index i in the string s is equal to the target character c. If they match, it increments the res variable by 1. After processing all characters in the string, the function returns the final count stored in res.
2. main function:-The main function is the entry point of the program.
It declares a string variable str to store the input string.
It uses cin to read a string input from the user and assigns it to the str variable.
It declares a character variable c to store the character to be counted.
It uses cin again to read a character input from the user and assigns it to the c variable.
It then calls the count function with the input string str and character c and prints the result (the count of occurrences) to the standard output using cout.
Finally, it returns 0, indicating successful program execution.

solution->

View Code 1
Time Complexity = O(n)
Space Complexity = O(n)