C++ Program to Find the Frequency of Characters in a String

In this post, you will learn how to Find the Frequency of Characters in a String using C++ programming language.

This lesson will teach you how to Find the Frequency of Characters in a String, with decision making statement, increment operator, and the for loop statement using the C++ Language. Let’s look at the below source code.

How to Find the Frequency of Characters in a String?

RUN CODE SNIPPET

Source Code

#include <iostream>
using namespace std;
int main() 
{
   char str[100] = "this line contains many alphabets";
   char c = 'a';
   int count = 0;
   for(int i = 0; str[i] != '\0'; i++) 
   {
      if(str[i] == c)
      count++;
   }
   cout<<"The string is :"<<endl; 
   cout<<"'this line contains many alphabets'"<<endl;
   cout<<endl;
   cout<<"Frequency of alphabet "<<c<<" in the string is "<<count;
   return 0;
}

Output

The string is :
'this line contains many alphabets'
Frequency of alphabet a in the string is 4

The statements #include<iostream>, using namespace std, int main are the main factors that support the function of the source code.

Now we can look into the working and layout of the code’s function.

  1. A string is a one-dimensional character array that ends with a null character. Frequency of characters in a string is the number of times they occur in a string. For example
    String: Music is an art The frequency of alphabet a in the above string is 2
  2. In the above code first declare the variable str as a character ( char ) and assign the string to the variable in double quotes ” “.
  3. Declare a variable cas a character to hold the alphabet to be counted ( in this code ‘a’), that is find the frequency(number of times it appears in the string). And declare the string count as as integer and assign its value as 0.
  4. Declare a for loop statement with the condition (int i = 0; str[i] != '\0'; i++) to verify the if the string is not a null value.
  5. In the body of the loop insert a decision making if statement with the condition (str[i] == c) which verifies the whether the selected alphabet from the string is similar to the alphabet in the variable in c, if the condition is true the value of the variable count is incremented.
  6. Finally display the string used in the code and the frequency of the character/alphabet in the string using the output function cout.