约 1756 字

约 9 分钟

#C 语言标准库函数 strpbrk

/*********************************************
 * @brief 在字符串中查找某个字符集合中的字符首次出现的位置
 * @param str 被检索的字符串
 * @param charset 要查找的字符集合
 * @return 首次出现的位置
 ********************************************/
char* strpbrk(const char* str, const char* charset);

说明

获取在字符串 str 中查找字符集合 charset 中的字符首次出现的位置。

参数

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

返回值

  • 集合中字符首次出现的位置

#示例

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

int main(void)
{
    const char* head = "Hello man, What can I say?";
    const char* charset = " ,.?!";

    const char* tail = NULL;
    while ((tail = strpbrk(head, charset)) != NULL) // 循环查找空格及标点符号
    {
        size_t len = strspn(tail, charset);  // 获取空格及标点符号的长度

        printf("单词: \"%.*s\"\n", (int)(tail - head), head);   // 分割打印单词

        head = tail + len;
    }

    return 0;
}

说明:

通过 strpbrk 查找空格及标点符号,从而实现单词的分割提取。

运行结果:

单词: "Hello"
单词: "man"
单词: "What"
单词: "can"
单词: "I"
单词: "say"

#推荐阅读

#参考标准

  • C23 standard (ISO/IEC 9899:2024):
    • 7.24.5.4 The strpbrk function (p: TBD)
  • C17 standard (ISO/IEC 9899:2018):
    • 7.24.5.4 The strpbrk function (p: TBD)
  • C11 standard (ISO/IEC 9899:2011):
    • 7.24.5.4 The strpbrk function (p: 368)
  • C99 standard (ISO/IEC 9899:1999):
    • 7.21.5.4 The strpbrk function (p: 331)
  • C89/C90 standard (ISO/IEC 9899:1990):
    • 4.11.5.4 The strpbrk function

更新: 2025/10/25

作者: PlanC

创建: 2025/7/12