假设您有一个char
八位系统,并且您尝试计算的所有字符都使用非负数编码。在这种情况下,您可以编写:
const char *str = "The quick brown fox jumped over the lazy dog.";
int counts[256] = { 0 };
int i;
size_t len = strlen(str);
for (i = 0; i < len; i++) {
counts[(int)(str[i])]++;
}
for (i = 0; i < 256; i++) {
if ( count[i] != 0) {
printf("The %c. character has %d occurrences.\n", i, counts[i]);
}
}
请注意,这将计算字符串中的所有字符。如果你 100% 绝对肯定你的字符串里面只有字母(没有数字、没有空格、没有标点符号),那么 1. 要求“不区分大小写”开始有意义,2. 你可以减少条目的数量到英文字母表中的字符数(即 26),你可以这样写:
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
const char *str = "TheQuickBrownFoxJumpedOverTheLazyDog";
int counts[26] = { 0 };
int i;
size_t len = strlen(str);
for (i = 0; i < len; i++) {
// Just in order that we don't shout ourselves in the foot
char c = str[i];
if (!isalpha(c)) continue;
counts[(int)(tolower(c) - 'a')]++;
}
for (i = 0; i < 26; i++) {
printf("'%c' has %2d occurrences.\n", i + 'a', counts[i]);
}