strstr()函数

来源:互联网 发布:咫尺网络小程序收费 编辑:程序博客网 时间:2024/05/24 06:09

下面再来看看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.   
  5.   
  6. const char* StrStr(const char *str1, const char *str2)  
  7. {  
  8.       assert(NULL != str1 && NULL != str2);  
  9.         
  10.        
  11.       while(*str1 != '\0')  
  12.       {  
  13.           const char *p = str1;  
  14.           const char *q = str2;  
  15.           const char *res = NULL;  
  16.           if(*p == *q)  
  17.           {  
  18.                 res = p;  
  19.                 while(*p && *q && *p++ == *q++)  
  20.                 ;  
  21.                   
  22.                 if(*q == '\0')  
  23.                       return res;                      
  24.           }  
  25.           str1++;  
  26.       }  
  27.       return NULL;  
  28. }  
  29.   
  30.   
  31. int main()  
  32. {  
  33.     const char *str1 = "wangyang";  
  34.     const char *str2 = "ang";  
  35.     const char *res = StrStr(str1, str2);  
  36.       
  37.     if(res != NULL)  
  38.             cout<<res<<endl;  
  39.     else  
  40.         cout<<"NOT"<<endl;  
  41.           
  42.     system("pause");  
  43.               
  44. }  

 

 

 

原创粉丝点击