Print characters and their frequencies in order of occurrence in C++

C++Server Side ProgrammingProgramming

This problem, We are given a string of lowercase characters. and we have to find the frequencies of each character that occurs in the string. the below example when explaining more about the problem.

Input : “jskdk”
Output :
j 1
s 1
k 2
d 1

Explanation − In the String, the characters j, s, d occur once and k occurs twice. Hence, the output printed gives the above result.

Now let's create a logic to solve this problem. As stated we have to find the frequency of occurrence of each character in the string. One logical way is to traverse the string and count the frequency of occurrence of a character and store it in an array and then print the character along with their frequency of occurrence.

Algorithm

Step 1 : Create an array of size 26 that stores the frequency of characters in the string.
Step 2 : print all the characters along with their frequency of occurrence from the array.

Example

Now, let’s create a program to find the solution to this problem,

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   string str = "tutorialspoint";
   int n = str.size();
   int frequency[26];
   memset(frequency, 0, sizeof(frequency));
   for (int i = 0; i < n; i++)
      frequency[str[i] - 'a']++;
   for (int i = 0; i < n; i++) {
      if (frequency[str[i] - 'a'] != 0) {
         cout<<str[i]<<"\t"<<frequency[str[i] - 'a']<<"\n";
         frequency[str[i] - 'a'] = 0;
      }
   }
   return 0;
}

Output

t 3
u 1
o 2
r 1
i 2
a 1
l 1
s 1
p 1
n 1
raja
Published on 03-Jan-2020 12:39:23
Advertisements