在C ++中按出现的顺序打印字符及其频率

这个问题,我们给了一个小写字符的字符串。并且我们必须找到字符串中每个字符的出现频率。下面的示例在解释有关该问题的更多信息时。

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

说明-在字符串中,字符j,s,d出现一次,而k出现两次。因此,输出的打印结果为上述结果。

现在让我们创建一个逻辑来解决这个问题。如前 ,我们必须找到字符串中每个字符的出现频率。一种逻辑方法是遍历字符串并计算字符出现的频率并将其存储在数组中,然后将字符及其出现频率打印出来。

算法

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.

示例

现在,让我们创建一个程序来找到该问题的解决方案,

#include <bits/stdc++.h>
using namespace std;
int main(){
   string str = "nhooo";
   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;
}

输出结果

t 3
u 1
o 2
r 1
i 2
a 1
l 1
s 1
p 1
n 1