现在的位置: 首页 > 综合 > 正文

strstr函数的自己实现

2013年06月19日 ⁄ 综合 ⁄ 共 1169字 ⁄ 字号 评论关闭

reference to:

http://blog.csdn.net/wangyangkobe/article/details/6787516

http://baike.baidu.com/view/745156.htm

在计算机内存中,0,'\0',null,是一样的,值也是一样的,都是0。以数字的方式读取就是0,以字符串的方式读取就是'\0',以程序命令或者其他方式读取就是null(null的定义跟编译器有关,有的编译器定义null可能不是0)。

请用标准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.     if('\0' != *str2)
  11.     {
  12.    
        
    while('\0' != *str1)
  13.    
        
    {
  14.        
        
    for(int index = 0; *(str1 + index) == *(str2 +index); index++)
  15.             {
  16.                 if('\0'
    == *(str2 + index + 1))
  17.                 {
  18.                     return
    str1;
  19.                 }
  1.             }
  2.        
        
    str1++;
  3.    
        
    }
  4.     
  5.         return NULL;
  6.     }  
  7.     else
  8.     {
  9.    
        
    return str1;
  10.     }
  11. }
  12.   
  13. int main()  
  14. {  
  15.     const char *str1
    "wangyang";  
  16.     const char *str2[]
    = {"", "wx", 
    "ang"};  
  17.     for(int index = 0; index < 3; index++)
  18.     {
  19.     const char *res = StrStr(str1, str2[index]);  
  20.       
  21.     if(res != NULL)  
  22.             cout<<str2[index]<<":Find, start pointer
    is:"<<
    res<<endl;  
  23.     else  
  24.             cout<<str2[index]<<":Not Find"<<endl;
     
  25.     }
  26.     system("pause");  
  27.               
  28. }  

抱歉!评论已关闭.