c/c++ strstr()函数实现

本文内容已经移至我最新的个人博客,欢迎大家到我的新网站交流学习。 查看文章请点我。















































































函数名称:

strstr()

函数头文件:

string.h

函数原型:

char *strstr(const char*source,const char*obj);

函数功能:

在字符串source中查找字符串obj,若找到,返回找到位置处的指针,若找不到,返回NULL。

实现过程:

char *strstr(const char*source,const char*obj){//the implement of function
    assert(source!=NULL && obj!=NULL);//the value of source and obj should not be NULL
    int len=strlen(source);//the length of source
    for(int i=0;i<=len;i++,source++)//traverse the source
    {
      char *p=(char *)source;//assign the current value of source to *p
      for(char *q=(char *)obj;;p++,q++)//traverse the obj and check whether the substring is equal to source
      {
          if(*q=='\0')//if the end of obj,then the substring is equal to source
              return (char *)source;
          if(*q!=*p)//if some element is not equal
              break;
      }
    }
    return NULL;
}</span>


你可能感兴趣的:(C++,strstr)