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

In this example program, the frequency of occurrence of a character is checked for string objects.

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

Iterate over the given string S and increment the frequency of each character encountered by 1.

String in C++

A string is a collection of characters. There are two types of strings commonly used in C++ programming language:
•    Strings that are objects of string class (The Standard C++ Library string class)
•    C-strings (C-style Strings)
  In C++, you can create a string object for holding strings. Unlike using char arrays, string objects have no fixed length and can be extended as per your requirement.

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

For computing the frequency of characters in a string, the length of the given string is to be calculated. For this size() function is used.
size() function is used to return the size of the set container or the number of elements in the set container. Return Value: It returns the number of elements in the set container.
Then a for loop is iterated throughout the string until the end.
In each iteration, the occurrence of the character is checked. If found then the value of variable count which is already set to 0 is incremented by 1.
for (int i = 0; i < str.size(); i++)
    {
        if (str[i] ==  checkCharacter)
        {
            ++ count;
        }
    }

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