strstr函數的自己實現

請用標準C語言實現下列標準庫函數,設計中不得使用其他庫函數。
char *strstr(char *str1,char *str2);

在字符串str1中,尋找字串str2,若找到返回找到的位置,否則返回NULL

  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. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章