Examples to Understand the Problem
Example 1: Let the given string be “she sells seashells by the seashore” and the given character be ’s'.
str = “she sells seashells by the seashore”
ch = ’s'
There are eight occurrences of the character s in the given string.
Thus, the output is 8.
Example 2: Let the given string be “He threw three free throws” and the given character be ’e'.
str = “He threw three free throws”
ch = ’e'
There are six occurrences of the character e in the given string.
Thus, the output is 6.
Approach to Count the Total Occurrences of a Character in a String
You can find the count of total occurrences of a character in a string by following the approach below:
Initialize a counter variable to store the count of total occurrences of a character in a string. Traverse the string character by character. If the character of the string matches with the given character, increment the value of the count variable. Finally, return the counter variable.
C++ Program to Count the Total Occurrences of a Character in a String
Below is the C++ program to count the total occurrences of a character in a string:
Output:
Python Program to Count the Total Occurrences of a Character in a String
Below is the Python program to count the total occurrences of a character in a string:
Output:
JavaScript Program to Count the Total Occurrences of a Character in a String
Below is the JavaScript program to count the total occurrences of a character in a string:
Output:
Other Methods to Solve the Problem
You can find the count of total occurrences of a character in a string by other methods like recursion, regular expressions, library functions, etc. The iterative method used in this article is one of the simplest methods to solve this problem.
If you want to practice more problems on strings, check out problems like how to reverse a string, how to check if a string is a palindrome, how to find the total count of vowels, consonants, digits, and special characters in a string, etc.