非常教程

C参考手册

字符串 | Strings

strchr

在头文件<string.h>中定义

char * strchr(const char * str,int ch);

在由str指向的以空字符结尾的字节串(每个字符解释为无符号字符)中查找第一次出现的ch(在转换为char之后,就像通过(char)ch)。 终止空字符被认为是字符串的一部分,可以在搜索'\ 0'时找到。

如果str不是指向以空字符结尾的字节字符串的指针,则行为是未定义的。

参数

str

-

指向要分析的空字符串字符串的指针

ch

-

要搜索的字符

返回值

指向str中找到的字符的指针,如果没有找到这样的字符,则指向空指针。

#include <stdio.h>
#include <string.h>
 
int main(void)
{
  const char *str = "Try not. Do, or do not. There is no try.";
  char target = 'T';
  const char *result = str;
 
  while((result = strchr(result, target)) != NULL) {
    printf("Found '%c' starting at '%s'\n", target, result);
    ++result; // Increment result, otherwise we'll find target at the same location
  }
}

输出:

Found 'T' starting at 'Try not. Do, or do not. There is no try.'
Found 'T' starting at 'There is no try.'

参考

  • C11标准(ISO / IEC 9899:2011):
    • 7.24.5.2 strchr函数(p:367-368)
  • C99标准(ISO / IEC 9899:1999):
    • 7.21.5.2 strchr函数(p:330)
  • C89 / C90标准(ISO / IEC 9899:1990):
    • 4.11.5.2 strchr函数

扩展内容

strrchr

查找最后一次出现的字符(函数)

strpbrk

找到一个字符串中任何字符的第一个位置,另一个字符串(函数)

| 用于strchr的C ++文档 |

C

C 语言是一门通用计算机编程语言,应用广泛。C 语言的设计目标是提供一种能以简易的方式编译、处理低级存储器、产生少量的机器码以及不需要任何运行环境支持便能运行的编程语言。