我试图检查并查看是否提供了一系列字符 - 像这样
char array_values[] = { 'A','B','C','D','a','b','c','d' };
然后在多个字符串中运行一种字符匹配,例如.-
....
str1 = 'AACDBACBAabcAcddaAABD'
str2 = 'aacbdAABDCAaDDCBCAabc'
....
然后返回字符串中每个字符的计数。
我知道在python,R,perl中很容易完成,但我想用C来解决这个问题。 也许像正则表达式?有任何想法吗?
答案 0 :(得分:4)
在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]]);
}