Home C&C++函数库 c++ 语法 程序源码 Linux C库

strchr

函数   <cstring>

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


定位字符串中第一次出现的字符

返回一个指向C字符串str中第一次出现字符的指针。

结束空字符被认为是C字符串的一部分。因此,也可以通过定位它来获取指向字符串末尾的指针。

☲  参数


str
C字符串.

character
要定位的字符。它作为int的形式传递,但为了进行比较,它在内部被转换回char。

☉  返回值



指向str中第一次出现的字符的指针。
如果没有找到character ,函数返回一个空指针。

❆  可移植性



在C语言中,这个函数只声明为:

char * strchr ( const char *, int );

而不是c++中提供的两个重载版本。

☣  示例



/* strchr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "This is a sample string";
  char * pch;
  printf ("Looking for the 's' character in \"%s\"...\n",str);
  pch=strchr(str,'s');
  while (pch!=NULL)
  {
    printf ("found at %d\n",pch-str+1);
    pch=strchr(pch+1,'s');
  }
  return 0;
}

输出:
Looking for the 's' character in "This is a sample string"...
found at 4
found at 7
found at 11
found at 18

🍄  另请参阅



memchr 在内存块中查找字符(function )
strpbrk 查找字符串中的字符(function)
strrchr 查找字符串中最后出现的字符(function )

联系我们 免责声明 关于CandCplus 网站地图