1369

7 分钟

#C 语言标准库函数 strcspn

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

说明

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

参数

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

返回值

  • 最长前缀长度

#示例

#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/7/12

更新于 2025/8/1