写一个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='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\n", (i + 97), frequency[i]);
示例
下面给出的是计算字符串中每个字符频率的C程序-
#include输出结果#include #define MAX 100 //最大字符串大小 int main(){ char string[MAX]; int i, length; int frequency[20]; /* Input string from user */ printf("enter the string:\n "); 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 ='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("\nFrequency of all characters in string: \n"); for(i=0; i<20; i++){ /* If current character exists in given string */ if(frequency[i] != 0){ printf("'%c' = %d\n", (i + 97), frequency[i]); } } return 0; }
执行上述程序时,会产生以下结果-
enter the string: nhooo.com Frequency of all characters in string: 'a' = 1 'i' = 2 'l' = 1 'n' = 1 'o' = 2 'p' = 1 'r' = 1 's' = 1 't' = 3