1. 程式人生 > >C語言字串查詢知識點搬運

C語言字串查詢知識點搬運

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首次出現的位置。

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. int main(){
  5.     char *s "0123456789012345678901234567890";
  6.     char *p;
  7.     p strchr(s'5');
  8. printf("%ld\n", s);
  9.     printf("%ld\n", p);
  10. system("pause");
  11.     return 0;
  12. }

輸出結果:
12016464
12016469

2.  https://zhidao.baidu.com/question/265212596486109045.html

//#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);



當s1<s2時,返回為負數; 當s1==s2時,返回值= 0; 當s1>s2時,返回正數。 即:兩個 字元串自左向右逐個字元相比(按ASCII值大小相比較),直到出現不同的字元或遇'\0'為止。如: "A"<"B" "a">"A" "computer">"compare" 特別注意:strcmp(const char *s1,const char * s2)這裡面只能比較字串,即可用於比較兩個字串常量,或比較陣列和字串常量,不能比較數字等其他形式的引數。