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

We can find the frequency of characters in a string in C++ language. Lets us discuss about what is frequency of a character and how to find frequency of character in a string in C++ language.

Frequency of character in a string is how many times they present in a string. This frequency of string value is essential to find the anagram strings. We can find it in two ways of method. One is using for loop and the another one is using while loop.

For example consider a string RanjithKumar. Character a presents 2 times in the string. The frequency of character a is 2.

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

#include <iostream>
using namespace std;
int main() {
char str = "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 = "this string contains many alphabets";
int i = 0, alphabet = {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
Read Also : Find Transpose of a Matrix in C++

Final Words

I hope this article helps you to Find the Frequency of Characters in a String in C++ Program. If you face any issues please let me know via the comment section. Share this article with other C++ program developers via social networks.

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