按在 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 = "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;
}

輸出

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

更新於: 03-Jan-2020

490 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.