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
🍄 另请参阅