天天看點

strstr()函數

下面再來看看strstr()函數

功 能:在串中查找指定字元串的第一次出現

  用 法: char *strstr(char *str1, char *str2);

  strstr原型:extern char *strstr(char *haystack, char *needle);

  用法:#include <string.h>

  功能:從字元串haystack中尋找needle第一次出現的位置(不比較結束符NULL)。

  說明:傳回指向第一次出現needle位置的指針,如果沒找到則傳回NULL。

當然和上一個函數一樣輸出的的從查找的字元串開始後面所有的字元(查找的字元也包含)

舉例

  //strstr.c

  #include<syslib.h>

  #include<string.h>

  main()

  {

  char*s="Golden Global View";

  char*l="lob";

  char*p;

  clrscr();

  p=strstr(s,l);

  if(p)

  printf("%s",p);

  else

  printf("NotFound!");

  getchar();

  return0;

  }

  文法:* strstr(str1,str2)

  str1:被查找目标 string expression to search.

  str2:要查找對象 The string expression to find.

  該函數傳回str2第一次在str1中的位置,如果沒有找到,傳回NULL

  Thestrstr() function returns the ordinal

positionwithin str1 of the first occurrence of str2. If str2 is not

foundin str1, strstr() returns 0.

  例子:

  功能:從字串” string1 onexxx string2 oneyyy”中尋找”yyy”

  (假設xxx和yyy都是一個未知的字串)

  char*s=” string1 onexxx string2 oneyyy”;

  char*p;

  p=strstr(s,”string2”);

  if(!p)printf(“Not Found!”);

  p=strstr(p,”one”);

  if(!p)printf(“Not Found!”);

  p+=strlen(“one”)

  printf(“%s”,p);

  說明:如果直接寫語句p=strstr(s,”one”),則找到的是onexxx string2 oneyyy,不符合要求

  是以需采用二次查找法找到目标

 下面是一個實作此函數的程式

  1. include <iostream>  
  2. #include <cassert>  
  3. using namespace std;  
  4. const char* StrStr(const char *str1, const char *str2)  
  5. {  
  6.       assert(NULL != str1 && NULL != str2);  
  7.       while(*str1 != '\0')  
  8.       {  
  9.           const char *p = str1;  
  10.           const char *q = str2;  
  11.           const char *res = NULL;  
  12.           if(*p == *q)  
  13.           {  
  14.                 res = p;  
  15.                 while(*p && *q && *p++ == *q++)  
  16.                 ;  
  17.                 if(*q == '\0')  
  18.                       return res;                      
  19.           }  
  20.           str1++;  
  21.       }  
  22.       return NULL;  
  23. }  
  24. int main()  
  25. {  
  26.     const char *str1 = "wangyang";  
  27.     const char *str2 = "ang";  
  28.     const char *res = StrStr(str1, str2);  
  29.     if(res != NULL)  
  30.             cout<<res<<endl;  
  31.     else  
  32.         cout<<"NOT"<<endl;  
  33.     system("pause");  
  34. }  

繼續閱讀