strchr是 C 语言标准库中的一个函数,用于在字符串中查找指定字符第一次出现的位置;该函数与memchr函数类似,只不过memchr函数可应用于任意数据类型,而strchr函数只可应用于字符串。

strchr 函数头文件

strchr函数的头文件是<string.h>。在使用strchr函数之前,确保在你的 C 代码中包含这个头文件:

#include <string.h>

strchr 函数原型

char* strchr(const char* s, int c);

strchr函数定位s指向的字符串中c(转换为char)第一次出现的位置;终止符'\0'被视为字符串的一部分。

参数说明

  • s:指向要搜索的字符串;

  • c:要查找的字符,会被转换成char类型;

返回值

memchr函数返回所定位字符的指针;如果c不在字符串中,返回空指针NULL

strchr 示例代码

判断字符串中是否有空格

如果字符串中不存在空格,则strchr()应该返回NULL

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

bool contains_space(const char* src) {
    
    if (strchr(src, ' ') == NULL) {
        return false;
    }

    return true;
}

int main() {

    const char* str = "perfcode.com";

    if (contains_space(str)) {
        printf("the string contains a space.\n");
    }
    else {
        printf("the string does not contain a space.\n");
    }

    return 0;
}