题目:从键盘输入一大堆字符串,统计A、B、C、D的出现次数,最后出现次数由高到低输出字母和出现次数。
#include <stdio.h>
#include <string.h>
// 计算字符出现的次数
int jiShu(char test[], char a)
{
// 统计字符数
int n = 0;
// 遍历字符串
for (int i = 0; i<strlen(test); i++) {
// 如果字符串中出现a,n加1
if (test[i] == a) {
n++;
}
}
return n;
}
int main(int argc, const char * argv[]) {
// 提示用户输入,并进行存储
printf("请输入任意字符串:\n");
char input[1000];
scanf("%[^\n]", &input);
// 字母A出现的次数
int a = jiShu(input, 'A');
// 字母B出现的次数
int b = jiShu(input, 'B');
// 字母C出现的次数
int c = jiShu(input, 'C');
// 字母D出现的次数
int d = jiShu(input, 'D');
// 定义结构体数组保存次数和对应的字符并初始化
struct test{
// 次数
int n;
// 对应的字符
char c;
} array[4] = {{a, 'A'}, {b, 'B'}, {c, 'C'}, {d, 'D'}};
// 定义临时数组
struct test temp;
// 冒泡排序法
for (int i = 0; i<3; i++) {
for (int j = 0; j<3-i; j++) {
if (array[j].n < array[j+1].n) {
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
// 输出
for (int i = 0; i<4; i++) {
printf("%c出现了%d次\n", array[i].c, array[i].n);
}
return 0;
}