在 C 中最简单的方法是计算每个字符,无论它是否存在于 中array_values
,然后使用array_values
项作为计数数组的索引来获得结果:
int count[256];
for (int i = 0 ; i != 256 ; count[i++] = 0);
// The example works with a single string. For multiple strings,
// iterate over the strings from your source in a loop, assigning str
// and incrementing the counts for each of your strings.
char *str = "AACDBACBAabcAcddaAABD";
for (char *p = str ; *p ; count[(unsigned char)*p++]++);
char array_values[] = { 'A','B','C','D','a','b','c','d' };
for (int i = 0 ; i != 8 ; i++) {
printf("Found '%c' %d times", array_values[i], count[(unsigned char)array_values[i]]);
}
这是关于 ideone 的演示。