函式
<cstring>

strchr

const char * strchr ( const char * str, int character );      char * strchr (       char * str, int character );
在字串中定位字元首次出現的位置
返回一個指向 C 字串 strcharacter 首次出現位置的指標。

字串的終止空字元被視為 C 字串的一部分。因此,也可以定位該字元以獲取指向字串末尾的指標。

引數

str
C 字串。
character
要定位的字元。它作為其int型別提升傳遞,但在內部會轉換回 char 進行比較。

返回值

一個指向 strcharacter 首次出現位置的指標。
如果未找到該 character,函式返回一個空指標。

可移植性

在 C 語言中,此函式僅宣告為

char * strchr ( const char *, int );

而不是 C++ 中提供的兩個過載版本。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* 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


另見