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

Hi Hello, What I am going to do in this article I will see in detail about C++ Program to Find the Frequency of Characters in a String. This article is a favorite of everyone and many people are suffering without knowing what the reason is. This article will be very useful for them.

The frequency of character in any string means how many times a particular character is present in any string.

Let the given string be “Codingdeekshi”. The character ‘e’ occurs 2 times in the given string and all the other characters occur only once. Thus, the character ‘e’ has the highest frequency in the given string.

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

Find the Frequency of Characters in a String in C++ Using For Loop

#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

Find the Frequency of Characters in a String in C++ Using While Loop

#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;
}

Read Also: Find Area of Circle in C++

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

Final Words

By knowing clearly about C++ Program to Find the Frequency of Characters in a String through this article. If you have any doubts please leave a comment via the comment box. Thank You.

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment