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

C++ProgrammingServer Side Programming

A string is a one-dimensional character array that is terminated by a null character. Frequency of characters in a string is the number of times they occur in a string. For example −

String: Football is a sport
The frequency of alphabet o in the above string is 3

A program to find the frequency of a particular alphabet is given as follows.

Example

 Live Demo

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

Output

Frequency of alphabet a in the string is 4

In the above program, for loop is used to find the frequency of alphabet a for the string given. In the for loop, if str[i] is equal to the alphabet, then count is incremented by 1. This value of count is displayed as the frequency of the alphabet. The code snippet for this is given as follows.

for(int i = 0; str[i] != '\0'; i++) {
   if(str[i] == c)
   count++;
}
cout<<"Frequency of alphabet "<<c<<" in the string is "<<count;

The program to find the frequency of all the alphabets in the string is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   char str[100] = "this string contains many alphabets";
   int i = 0, alphabet[26] = {0}, j;
   while (str[i] != '\0') {
      if (str[i] >= 'a' && str[i] <= 'z') {
         j = str[i] - 'a';
         ++alphabet[j];
      }
      ++i;
   }
   cout<<"Frequency of all alphabets in the string is:"<<endl;
   for (i = 0; i < 26; i++)
   cout<< char(i + 'a')<<" : "<< alphabet[i]<< endl;
   return 0;
}

Output

Frequency of all alphabets in the string is:
a : 4
b : 1
c : 1
d : 0
e : 1
f : 0
g : 1
h : 2
i : 3
j : 0
k : 0
l : 1
m : 1
n : 4
o : 1
p : 1
q : 0
r : 1
s : 4
t : 4
u : 0
v : 0
w : 0
x : 0
y : 1
z : 0

In the above program, a while loop is used to find the frequency of all the alphabets in the string. An array alphabet[] stores the frequency of all the alphabets. The variable j stores the numerical value of the alphabet i.e a is 0, b is 1 and so on. Then the jth index of the array alphabet is incremented by 1. This is demonstrated by the following code snippet −

while (str[i] != '\0') {
   if (str[i] >= 'a' && str[i] <= 'z') {
      j = str[i] - 'a';
      ++alphabet[j];
   }
   ++i;
}

After the whole string is evaluated, the frequency of the alphabets is printed. This is shown as follows.

cout<<"Frequency of all alphabets in the string is:"<<endl;
for (i = 0; i < 26; i++)
cout<< char(i + 'a')<<" : "<< alphabet[i]<< endl;
raja
Published on 05-Oct-2018 07:44:39
Advertisements