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

# C 语言标准库函数 strpbrk

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

!subtitle:说明

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

!subtitle:参数

  • str - 被检索的字符串

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

!subtitle:返回值

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

# 示例

#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-11-27 09:38:10 创建于: 2025-11-27 09:38:10