gpt4 book ai didi

c - 如何使用strspn查找strspn的arg 2中提到的字符数以外的字符数?

转载 作者:太空宇宙 更新时间:2023-11-04 00:10:47 24 4
gpt4 key购买 nike

如何计算 strspn 函数中提到的值以外的值的数量?我知道 strspn 计算参数 2 中提到的字符的总出现次数,但我想做相反的事情。

例如,如果我有字符串:ABCDEFGH

我想统计D以外的字符数。所以答案是:7

无论如何我可以用 strspn 做到这一点吗?

最佳答案

你想计算个不匹配集合的字符,你需要自己实现这个函数,用一个循环:

size_t count_non_matching_chars(const char *str, const char *set) {
size_t pos = 0, count = 0, chunk;

while (str[pos] != '\0') {
pos += strspn(str + pos, set); /* skip the matching chars */
chunk = strcspn(str + pos, set); /* count non matching chars */
pos += chunk;
count += chunk;
}
return count;
}

这是一个只使用 strspn() 的替代方案,如果有很多不匹配的字符,效率会稍微低一些:

size_t count_non_matching_chars(const char *str, const char *set) {
size_t pos = 0, count = 0;
for (;;) {
pos += strspn(str + pos, set); /* skip the matching chars */
if (str[pos] == '\0')
break;
count++; /* count and skip the non-matching character */
pos++;
}
return count;
}

关于c - 如何使用strspn查找strspn的arg 2中提到的字符数以外的字符数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35367210/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com