在 C 语言 中我们要在一个 字符串 中查找某一个 字符 ,我们可以使用 strchr 函数。strchr 函数会返回要查找的字符在字符串中第一次出现的位置。
char *strchr(const char *str, int c);
参数 | 描述 |
---|---|
str | 要被检索的 C 字符串。 |
c | 在 str 中要搜索的字符。 |
该函数返回在字符串 str 中第一次出现字符 c 的位置,如果未找到该字符则返回 NULL。
使用 strchr 函数,需要引入 string.h 头文件。
使用 strchr() 函数,实现查找字符串字符
#include <stdio.h>
#include <string.h>
int main()
{
printf("嗨客网(www.haicoder.net)\n\n");
char str1[30] = "Hello,HaiCoder";
char ch = ',';
char* retCh = strchr(str1, ch);
printf("retCh = %s\n", retCh);
return 0;
}
程序运行后,控制台输出如下:
我们首先定义了一个 字符数组 str1 和一个字符 ch,并赋值,接着,我们使用了 strchr 函数在字符串 str1 中查找字符 ch,并将查找到的字符串赋值给 变量 retCh。
使用 strchr() 函数,实现查找字符串字符
#include <stdio.h>
#include <string.h>
int main()
{
printf("嗨客网(www.haicoder.net)\n\n");
char str1[30] = "Hello,HaiCoder";
char ch = 'b';
char* retCh = strchr(str1, ch);
printf("retCh = %s\n", retCh);
return 0;
}
程序运行后,控制台输出如下:
我们首先定义了一个字符数组 str1 和一个字符 ch,并赋值,接着,我们使用了 strchr 函数在字符串 str1 中查找字符 ch,因为,没有查找到字符 ch,因此,返回了 NULL。
在 C 语言中我们要在一个字符串中查找某一个字符 ,我们可以使用 strchr 函数。strchr 函数会返回要查找的字符在字符串中第一次出现的位置。