讓我們假設你有一個系統,其中char
是8位,你試圖計數的所有字符都是用非負數編碼的。在這種情況下,您可以編寫:
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++) {
printf("The %d. 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]);
}
此代碼給我這個: 0.字符有0次出現。 1.字符出現0次。 ..... – enginefree
@ user1786283你列出的是**短跑**('-')。我不相信你明白了。 – 2012-11-03 21:23:48
@ user1786283 Aaaaaaand ...那有什麼不對?這意味着字符「0x00」沒有出現。等等。您知道,如果您使用的是基於GUI的現代操作系統,終端窗口右側會出現一個滾動條。另外,你是否努力嘗試第二個代碼被剪切? – 2012-11-03 21:25:52