繁体   English   中英

有什么方法可以检查C中的字符串中是否存在任何或所有字符?

[英]Is there any way to check if any or all characters are present in a string in C?

我正在尝试检查是否给出字符数组-像这样

char  array_values[] = { 'A','B','C','D','a','b','c','d' };

然后在多个字符串中运行某种字符匹配,例如-

....
str1 = 'AACDBACBAabcAcddaAABD'
str2 = 'aacbdAABDCAaDDCBCAabc'
....

然后返回字符串中存在的每个字符的计数。

我知道在python,R,perl中很容易做到,但是我想在C中弄清楚。也许像正则表达式一样? 有任何想法吗?

在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演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM