gpt4 book ai didi

计算一个字符在数组中出现的次数

转载 作者:行者123 更新时间:2023-11-30 19:32:41 24 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define N 100

int main()
{

int count[26] = {0};
int i;
char ch ='a';

printf("Enter a sentence (end by '.'): ");

while (ch != '.') {
ch = getchar();

count[(tolower(ch) - 'a')]++;

for (i = 0; i < 26; i++) {
printf("'%c' has %2d occurrences.\n", i + 'a', count[i]);
}
}

return 0;
}

程序做了它应该做的事情。计数器工作正常,问题是程序对每个字母运行两次并打印出哪些字母出现了 0 次。正确的输出应该如下:

输入以“.”结尾的句子

scanf 读取此内容。

正确输出:

T 出现 1 次

H 出现 1 次

I出现1次

S出现1次

但是代码的输出会遍历每个字母,并打印出哪些字母根本没有出现。我需要去掉出现“0 次”的字母,只显示出现 1 次或多次的字母。

如有任何帮助,我们将不胜感激!

最佳答案

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define N 100

int main()

{

int count[26] = {0};
int i;
char ch ='a';

printf("Enter a sentence (end by '.'): ");

while (ch != '.') {
ch = getchar();

count[(tolower(ch) - 'a')]++;

for (i = 0; i < 26; i++) {
if (count[i] > 0) {
printf("'%c' has %2d occurrences.\n", i + 'a', count[i]);
}
}
}

return 0;

}

关于计算一个字符在数组中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46778236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com