C語言字串查詢知識點搬運
阿新 • • 發佈:2018-11-27
1.
標頭檔案:#include <string.h>
strchr() 用來查詢某字元在字串中首次出現的位置,其原型為:
char * strchr (const char *str, int c);
【引數】str 為要查詢的字串,c 為要查詢的字元。
strchr() 將會找出 str 字串中第一次出現的字元 c 的地址,然後將該地址返回。
注意:字串 str 的結束標誌 NUL 也會被納入檢索範圍,所以 str 的組後一個字元也可以被定位。
【返回值】如果找到指定的字元則返回該字元所在地址,否則返回 NULL。
返回的地址是字串在記憶體中隨機分配的地址再加上你所搜尋的字元在字串位置。設字元在字串中首次出現的位置為 i,那麼返回的地址可以理解為 str + i。
提示:如果希望查詢某字元在字串中最後一次出現的位置,可以使用 strrchr() 函式。
【例項】查詢字元5首次出現的位置。
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- int main(){
- char *s = "0123456789012345678901234567890";
- char *p;
- p = strchr(s, '5');
- printf("%ld\n", s);
- printf("%ld\n", p);
- system("pause");
- return 0;
- }
輸出結果:
12016464
12016469
//#include "stdafx.h"//If the vc++6.0, with this line.
#include "stdio.h"
#include "string.h"
int
main(
void
){
char
a[50]=
"1234567890"
,b[10]=
"345"
,*pt;
if
(pt=
strstr
(a,b))
printf
(
"From %d of the beginning.\n"
,pt-a);
else
printf
(
"Not find \'%s\'.\n"
,b);
return
0;
}
3.
extern
int
strcmp
(
const
char
*s1,
const
char
*s2);