我想要一个计算数组中字母出现次数的代码.我已经查看了各种准确的代码,但它们都使用字符串.我的问题是严格使用数组.我创建了一个代码,但它返回:: 0 : 1 : 2 : 3 : 4 : 5 : 6 : 7 : ...
一个正确的例子: 输入:
The quick brown fox jumps over the lazy dog.
Run Code Online (Sandbox Code Playgroud)
输出:
A: 1
B: 1
C: 1
D: 1
E: 3
F: 1 ...
Run Code Online (Sandbox Code Playgroud)
以下是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
int i = 0;
int c;
char counts[26] = {0};
c = getchar();
while (c != EOF && i < 26) {
counts[i] = c;
i += 1;
c = getchar();
}
for (i = 0; i < 26; i++) {
if (counts[i] !=0 )
printf("%c: %d", toupper(c), i);
}
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
LPs*_*LPs 10
使用你的代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
int c;
int counts['Z' - 'A'] = {0};
c = getchar();
while (c != EOF)
{
if (isalpha(c))
counts[(toupper(c)-'A')]++;
c = getchar();
}
for (unsigned int i = 0; i < sizeof(counts)/sizeof(counts[0]); i++)
{
if (counts[i] !=0 )
printf("%c: %d\n", 'A'+i, counts[i]);
}
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
(toupper(c)-'A')了使得输入char 0的索引值.if (isalpha(c))去做.