C语言编写一个算法统计在输入字符串中各个不同字符出现的频度,并将结果输出(字符串中的合法字符为a-z、A-Z之间的26个字母和0-9之间的10个数字)。
时间: 2024-10-14 12:06:04 浏览: 36
在C语言中,我们可以创建一个简单的程序来实现这个功能,利用哈希表(例如数组或结构体)存储每个字符及其出现次数。下面是一个基本的实现步骤:
```c
#include <stdio.h>
#include <string.h>
#define ALPHABET_SIZE 26
#define DIGITS_SIZE 10
typedef struct {
char ch;
int count;
} Frequency;
void computeFrequency(const char *str, Frequency freqs[ALPHABET_SIZE + DIGITS_SIZE]) {
for (int i = 0; str[i] != '\0'; ++i) {
if ('a' <= str[i] && str[i] <= 'z') {
freqs[str[i] - 'a'].count++;
} else if ('A' <= str[i] && str[i] <= 'Z') {
freqs[str[i] - 'A'].count++;
} else if ('0' <= str[i] && str[i] <= '9') {
freqs[str[i] - '0'].count++;
}
}
}
void printFrequency(Frequency freqs[], int size) {
printf("Character\tFrequency\n");
for (int i = 0; i < size; ++i) {
if (freqs[i].count > 0) {
printf("%c\t%d\n", freqs[i].ch, freqs[i].count);
}
}
}
int main() {
char input[100];
printf("Enter a string: ");
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = '\0'; // Remove newline character from the end of the input
Frequency freqs[ALPHABET_SIZE + DIGITS_SIZE] = {0};
computeFrequency(input, freqs);
printFrequency(freqs, ALPHABET_SIZE + DIGITS_SIZE);
return 0;
}
阅读全文