strstr函数的实现

来源:互联网 发布:淘宝食品店需要什么 编辑:程序博客网 时间:2024/05/19 00:08
函数要求:使用标准C语言实现下列标准库函数,设计中不得使用其他库函数。
函数原型:char *strstr(char *str1,char *str2);
说明:在字符串str1中,寻找字串str2,若找到返回找到的位置,否则返回NULL。

实现代码如下:

  1. #include <stdio.h>
  2. #include <errno.h>
  3. #include <assert.h>
  4. char *strstr(const char *find,const char *need);
  5. int main()
  6. {
  7.     const char buf1[100] = "heelor";
  8.     const char buf2[100] = "lor";
  9.     
  10.     const char *res =strstr(buf1,buf2);
  11.     printf("the res=%s",res);
  12.     return 0;


  13. }

  14. char *strstr(const char *find, const char *need)
  15. {
  16.     assert(find !=NULL && need !=NULL);

  17.     while( *find !='\0')
  18.     {
  19.     const char *p=find;
  20.     const char *q =need;
  21.     const char *res= NULL;


  22.     if(*p == *q)
  23.         {    
  24.         res= p;
  25.         while(*p++ == *q++)
  26.             ;
  27.         if(*q == '\0')
  28.         return res;

  29.     
  30.         }
  31.     find ++;
  32.     }
  33.     return NULL;

  34. }

1 0