編寫一個 C 程式來統計每個字元的出現頻率


遵循演算法編寫一個 C 程式,該程式能夠統計每個字元的頻率。

演算法

Step 1: Define MAX size.
Step 2: Declare char and integer variables.
Step 3: Read the string from console.
Step 4: Find length of the string.
Step 5: Initialize frequency of each character to 0.
Step 6: Find total number of occurrences of each character.
for(i=0; i<length; i++)
   i. if(string[i]>='a' && string[i]<='z')
   frequency[string[i] - 97]++;
   ii. else if(string[i]>='A' && string[i]<='Z')
      frequency[string[i] - 65]++;
Step 7: Print the frequency of all characters in the string.
if(frequency[i] != 0)
   printf("'%c' = %d
", (i + 97), frequency[i]);

示例

下面給出一個 C 程式,用於統計字串中每個字元的頻率 −

程式碼演示

#include <stdio.h>
#include <string.h>
#define MAX 100 // Maximum string size
int main(){
   char string[MAX];
   int i, length;
   int frequency[20];
   /* Input string from user */
   printf("enter the string:
");    gets(string);    length = strlen(string);    /* Initialize frequency of each character to 0 */    for(i=0; i<20; i++){       frequency[i] = 0;    }    /* Find total number of occurrences of each character */    for(i=0; i<length; i++){       /* If the current character is lowercase alphabet */       if(string[i]>='a' && string[i]<='z'){          frequency[string[i] - 97]++;       }       else if(string[i]>='A' && string[i]<='Z'){          frequency[string[i] - 65]++;       }    }    /* Print the frequency of all characters in the string */    printf("
Frequency of all characters in string:
");    for(i=0; i<20; i++){       /* If current character exists in given string */       if(frequency[i] != 0){          printf("'%c' = %d
", (i + 97), frequency[i]);       }    }    return 0; }

輸出

當執行上述程式時,將產生以下結果 −

enter the string:
Tutorials Point
Frequency of all characters in string:
'a' = 1
'i' = 2
'l' = 1
'n' = 1
'o' = 2
'p' = 1
'r' = 1
's' = 1
't' = 3

更新於:2021 年 3 月 24 日

657 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

入門
廣告