C++ Program to find the frequency of characters in a string


January 21, 2023, Learn eTutorial
1388

Define String in C++.

A string can be defined as a collection of characters to form a meaningful or meaningless word.

How to find the frequency of occurrence of a character in a string?

For finding the frequency of a character in a string, we have to traverse through the string and increment a counter if we reach the specified character.

C++ program to find the frequency of characters of a string object

For calculating the frequency of character in a string, we have to find the length of the string. For this, we have to use the function size()

size() function is a C++ built-in function that will return the size or number of characters in the string. Then a for loop is iterated throughout the string until the end of the string. In each iteration, we check for the character. If found then the value of the variable count incremented by 1. Finally, display the value of the count on the screen.

Algorithm

Step 1:  Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Open the integer type main function; int main().

Step 4: Declare a string type variable str= “learnetutorials is very useful”;

Step 5: set the character to be checked to a character variable checkcharacter

Step 6: Initialize the value of variable count to 0;

Step 7: Calculate the length of the string using the function size();

Step 8:Iterate through the string using a for loop until the last character.

Step 9: check for each character if it is equal to checkcharacter;

Step 10:Increment the value of count by 1 if yes.

Step 11: display the value of the count

Step 12:exit;
 

C++ Source Code

                                          #include <iostream>
using namespace std;

int main()
{
    string str = "learnetutorials is very useful";
    char checkCharacter = 'e';
    int count = 0;

    for (int i = 0; i < str.size(); i++)
    {
        if (str[i] ==  checkCharacter)
        {
            ++ count;
        }
    }

    cout << "Number of " << checkCharacter << " = " << count;

    return 0;
}
                                      

OUTPUT

Number of e = 4