p124数组案例：字母次数统计

p124 数组案例：字母次数统计

Copy
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <limits.h>
#include <ctype.h>

#define LETTER_COUNT 26

int main(void)
{
uint32_t frequency[LETTER_COUNT] = { 0 };

char text[] = "Example text for frequency analysis.\0";

// 统计每个字母出现的次数
for (uint32_t i = 0; text[i] != '\0'; i++)
{
char ch = tolower(text[i]);

if (ch >= 'a' && ch <= 'z') {
frequency[ch - 'a']++;
}
}

puts("Character Frequency:\n");
for (int i = 0; i < LETTER_COUNT; i++) {
if (frequency[i] > 0) {
printf("'%c': %d\n", 'a' + i, frequency[i]);
}
}
return 0;
}

加强后：

Copy
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <limits.h>
#include <ctype.h>
#include <string.h> // 包含 strcspn 函数

#define LETTER_COUNT 26
#define MAX_TEXT_LENGTH 256 // 定义最大输入长度

int main(void)
{
uint32_t frequency[LETTER_COUNT] = { 0 };

char text[MAX_TEXT_LENGTH]; // 用于存储用户输入的文本

//char text[] = "Example text for frequency analysis.\0";
printf("请输入文本: ");
fgets(text, sizeof(text), stdin); // 使用 fgets 读取一行文本

//处理换行符
text[strcspn(text, "\n")] = '\0'; // 将换行符替换为字符串结束符

//统计每个字母出现的次数
for (uint32_t i = 0; text[i] != '\0'; i++)
{
char ch = tolower(text[i]);

if (ch >= 'a' && ch <= 'z') {
frequency[ch - 'a']++;
}
}
puts("Character Frequency:\n");
for (int i = 0; i < LETTER_COUNT; i++) {
if (frequency[i] > 0) {
printf("'%c': %d\n", 'a' + i, frequency[i]);
}
}
return 0;
}

此文由 Mix Space 同步更新至 xLog
原始链接为 https://hansblog.top/posts/study-book/c-p124