国际访客建议访问 Primers 编程伙伴 国际版站点 > C 教程 > strcspn 以获得更好的体验。

# C 语言标准库函数 strcspn

在头文件 string.h 中定义。
/*********************************************
 * @brief 在字符串中查找不含某些字符的最长前缀长度
 * @param str 被检索的字符串
 * @param charset 要查找的字符集合
 * @return 集合中的字符在字符串
 ********************************************/
size_t strcspn(const char* str, const char* charset);

!subtitle:说明

获取在字符串 str 开头,不含字符集合 charset 中字符的最长前缀长度。

!subtitle:参数

  • str - 被检索的字符串

  • charset - 被搜索的字符集合组成的字符串

!subtitle:返回值

  • 最长前缀长度

# 示例

#include <stdio.h>
#include <string.h>

int main(void)
{
    const char* text = "ZZEEAACBCDDAA";
    const char* charset = "ABC";
    size_t len = strcspn(text, charset);  // 查找不含 ABC 的最长前缀
    printf("\"%s\" 中不含 \"%s\" 中字符的最长前缀为 \"%.*s\"\n", text, charset, (int)len, text);

    return 0;
}

说明:

通过 strcspn 查找 "ZZEEAACBCDDAA" 中不含 "ABC" 的最长前缀长度;并根据该长度打印前缀。

运行结果:

"ZZEEAACBCDDAA" 中不含 "ABC" 中字符的最长前缀为 "ZZEE"

# 推荐阅读

# 参考标准

  • C11 standard (ISO/IEC 9899:2011):

    • 7.24.5.3 The strcspn function (p: 368)

  • C99 standard (ISO/IEC 9899:1999):

    • 7.21.5.3 The strcspn function (p: 331)

  • C89/C90 standard (ISO/IEC 9899:1990):

    • 4.11.5.3 The strcspn function

本文 更新于: 2025-11-27 09:38:10 创建于: 2025-11-27 09:38:10