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

C 如何使用strspn查找strspn arg 2中提到的字符以外的字符数?,c,string,C,String,除了在strspn函数中提到的值之外,我如何计算其他值的数量?我知道strspn会计算参数2中提到的字符的总出现次数,但我想做的是相反的事情 例如,如果我有字符串:ABCDEFGH 我想计算D以外的字符数。所以答案是:7 我是否可以使用strspn执行此操作?尝试从字符串的总长度中减去strspn的结果: strlen(string) - strspn(string); 尝试从字符串的总长度中减去strspn的结果: strlen(string) - strspn(string); 使用st

除了在
strspn
函数中提到的值之外,我如何计算其他值的数量?我知道strspn会计算参数2中提到的字符的总出现次数,但我想做的是相反的事情

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

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


我是否可以使用strspn
执行此操作?

尝试从字符串的总长度中减去strspn的结果:

strlen(string) - strspn(string);

尝试从字符串的总长度中减去strspn的结果:

strlen(string) - strspn(string);
使用
strcspn(str,set)
函数,该函数与
strspn(str,set)
类似,但可用于
set
的补码。请注意,终止的
'\0'
通常是
set
的隐式部分,因此不被
strcspn()计算

使用
strcspn(str,set)
函数,该函数与
strspn(str,set)
类似,但作用于
set
的补码。请注意,终止的
'\0'
通常隐式地是
集合的一部分,因此不被
strcspn()

计算与集合不匹配的字符总数,您需要使用循环自己实现此函数:

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;
}
如果要计算与集合不匹配的字符总数,则需要使用循环自己实现此函数:

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;
}

strspn(str,set)
并没有完全按照你的想法去做。它返回
str
的最长前缀的长度,所有字符都在
集合中,而不是整个计数。详细信息:字符串
“ABCDEFGH”
由9个
字符组成。因此,目标似乎是“计算除
'D'
'\0'
之外的字符数”。
strspn(str,set)
并没有完全按照您的想法执行。它返回
str
的最长前缀的长度,所有字符都在
集合中,而不是整个计数。详细信息:字符串
“ABCDEFGH”
由9个
字符组成。因此,目标似乎是“计算除
'D'
'\0'
之外的字符数”。实际上,这是计算从第一个不匹配的字符到字符串结尾的字符数。此外,
strspn
的语法不正确,这会计算从第一个不匹配的字符到字符串结尾的字符数。此外,
strspn
strcspn()
的语法不正确,返回初始计数时,OP需要总计数。
strcspn()
返回初始计数时,OP需要总计数。根据OP请求的Nice code“使用strspn执行此操作”+1。根据OP请求的Nice code“使用strspn执行此操作”+1。