-
strchr
鎖定
- 中文名
- strchr
- 外文名
- strchr
- 應 用
- C語言編程
- 類 別
- 庫函數
- 功 能
- 查找給定字符的第一個匹配之處
strchrC語言strchr函數
strchr函數原型
char *strchr(const char *str, int c)
strchr參數
- str-- 要被檢索的 C 字符串。
- c-- 在 str 中要搜索的字符。
strchr功能
在參數str所指向的字符串中搜索第一次出現字符c(一個無符號字符)的位置。
strchr返回值
strchr頭文件
#include <string.h>
strchrPHP語言
strchr語法
strchr(string,search,before_search);
strchr定義和用法
strchr() 函數搜索字符串在另一字符串中的第一次出現。
該函數是strstr()函數的別名。
註釋:該函數是二進制安全的。
strchr參數
參數 | 描述 |
---|---|
string | 必需。規定被搜索的字符串。 |
search | 必需。規定所搜索的字符串。如果該參數是數字,則搜索匹配該數字對應的 ASCII 值的字符。 |
before_search | 可選。一個默認值為 "false" 的布爾值。如果設置為 "true",它將返回search參數第一次出現之前的字符串部分。 |
strchr示例
<?php $email='name@example.com'; $domain=strchr($email,'@'); echo$domain;//打印@example.com $user=strchr($email,'@',true);//從PHP5.3.0起 echo$user;//打印name ?>
strchr函數公式
實現:
char* strchr(char *s, char c) { while(*s != '\0' && *s != c) { ++s; } return *s==c ? s : NULL; }
strchr應用範例
strchr示例1
(在Visual C++ 6.0中運行通過)
#include <string.h> #include <stdio.h> int main(void) { char string[17]; char *ptr,c='r'; strcpy(string,"Thisisastring"); ptr=strchr(string,c); if(ptr) printf("The character %cis at position:%s\n",c,ptr); else printf("The character was not found\n"); return 0; }
運行結果:
The character r is at position: ring
請按任意鍵繼續. . .
strchr示例2
// strchr.c #include <stdio.h> #include <string.h> int main() { char temp[32]; memset(temp,0,sizeof(temp)); strcpy(temp,"Golden Global View"); char *s = temp; char *p,c='v'; p=strchr(s,c); if(p) printf("%s",p); else printf("Not Found!"); return 0; }
運行結果:Not Found!Press any key to continue
strchr示例3
#include <stdio.h> #include <string.h> void main() { char answer[100],*p; printf("Type something:\n"); fgets(answer,sizeof answer,stdin); if((p = strchr(answer,'\n')) != NULL) *p = '\0';//手動將\n位置處的值變為0 printf("You typed \"%s\"\n",answer); }
fgets不會像gets那樣自動地去掉結尾的\n,所以程序中手動將\n位置處的值變為\0,代表輸入的結束。