C++

Summary of the implementation method of C++ function strstr


Summary of the implementation method of strstr function in C++

Function description:

Include file: string.h

Function name: strstr

Function prototype: extern char *strstr(char *str1, char *str2);

Function: find the string str2 from str1, if so, return a pointer to str1 from str2 in str1, if not, null.

Return value: returns a pointer to the location. If it cannot be found, returns a null pointer.

Method 1:

#include <iostream>
#include <assert.h>
using namespace std;

char* My_strstr(char *src,char *substr)
{
  assert(src != NULL && substr != NULL);

  unsigned int size = strlen(src);
  for(int i = 0; i < size; ++i,++src)
  {
    char *p = src;
    for(char *q = substr;;p++,q++)
    {
      if(*q == '\0')  // in src Find the continuous in substr The substring stops and returns
      {
        return src;
      }
      if(*q != *p)
      {
        break;
      }
    }
  }

  return NULL;
}

int main()
{
  char *res = My_strstr("abcdefg","cde");
  if(res != NULL)
  {
    cout<<"exist:"<<res<<endl;
  }
  else
  {
    cout<<"no exist!"<<endl;
  }
  return 0;
}

Method 2:

#include <iostream>
#include <assert.h>
using namespace std;
char* My_strstr(const char* s1,const char* s2)
{
  int n;
  if(*s2)
  {
    while(*s1)
    {
      for(n=0;*(s1+n)==*(s2+n);n++)
      {
        if(!*(s2+n+1))
          return (char*)s1;
      }
      s1++;
    }
    return NULL;
  }
  else
    return (char*)s1;
}

int main()
{
  char *res = My_strstr("abcdefg","cde");
  if(res != NULL)
  {
    cout<<"exist:"<<res<<endl;
  }
  else
  {
    cout<<"no exist!"<<endl;
  }
  return 0;
}

Method 3:

#include <iostream>
#include <assert.h>
using namespace std;
char* My_strstr(const char* s1,const char* s2)
{
  const char *p=s1;
  const size_t len=strlen(s2);
  for(;(p=strchr(p,*s2))!=0;p++)// strchr Find string s The first character to appear in c The location of the
  {
    if(strncmp(p,s2,len)==0)
    {
      return(char*)p;
    }
  }
  return(0);
}
int main()
{
  char *res = My_strstr("abcdefg","cde");
  if(res != NULL)
  {
    cout<<"exist:"<<res<<endl;
  }
  else
  {
    cout<<"no exist!"<<endl;
  }
  return 0;
}

If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!