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

# C 语言标准库函数 strchr

在头文件 string.h 中定义。
/*********************************************
 * @brief 在字符串中查找字符
 * @param str 被检索的字符串
 * @param ch 要查找的字符
 * @return 指向找到的字符的指针
 ********************************************/
char* strchr(const char* str, int ch);

!subtitle:说明

在字符串 str 中查找 ch 字符,返回找到的第一个 ch 字符的地址。

!subtitle:参数

  • str - 被检索的字符串

  • ch - 要查找的字符

!subtitle:返回值

  • 指向找到的字符的指针

  • 如果没有找到目标字符,则返回 NULL

# 示例

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

int main(void)
{
    const char* text = "hello world";

    const char* str = text;
    while ((str = strchr(str, 'l')) != NULL) // 循环查找 'l'
    {
        printf("地址:%p 偏移:%td 字符:'%c' 剩余字符串:\"%s\"\n", str, str - text, *str, str);
        str += 1;
    }

    return 0;
}

说明:

通过 strchr 循环查找字母 'l' 直到返回 NULL

运行结果:

地址:0x62e1dbf6d00a 偏移:2 字符:'l' 剩余字符串:"llo world"
地址:0x62e1dbf6d00b 偏移:3 字符:'l' 剩余字符串:"lo world"
地址:0x62e1dbf6d011 偏移:9 字符:'l' 剩余字符串:"ld"

# 推荐阅读

# 参考标准

  • C23 standard (ISO/IEC 9899:2024):

    • 7.24.5.2 The strchr function (p: TBD)

  • C17 standard (ISO/IEC 9899:2018):

    • 7.24.5.2 The strchr function (p: TBD)

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

    • 7.24.5.2 The strchr function (p: 367-368)

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

    • 7.21.5.2 The strchr function (p: 330)

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

    • 4.11.5.2 The strchr function

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