strstr through pointers in c language

2019-07-31 03:36发布

is this the standard code for strstr i made????

char* fstrset(char *s,char *t)
{
    int b, i=0,j=0;

 while(*(s+i)!='\0')
 {
  if(*(t+j)=='\0')
   break;
  else if(*(s+i)==*(t+j))
   {
   i++;j++;b=1;
   }
  else
   { i++;b=0;j=0;
   }
 }

    if(b==0)
     return((char*)NULL);
    else if(b==1)
     return(s+i-j);
}

9条回答
爷、活的狠高调
2楼-- · 2019-07-31 04:37

This is all the standard has to say about it:

7.21.5.7 The strstr function

Synopsis

 #include <string.h> 
char *strstr(const char *s1, const char *s2); 

Description

The strstr function locates the first occurrence in the string pointed to by s1 of the sequence of characters (excluding the terminating null character) in the string pointed to by s2.

Returns

The strstr function returns a pointer to the located string, or a null pointer if the string is not found. If s2 points to a string with zero length, the function returns s1.

So, it looks like you're missing const qualifiers on arguments.

As for style, note that *(ptr+index) can be replaced by ptr[index], and size_t is the best type to use for indexing a pointer.

As for being a common way to implement it, compare with GCC's code:

char *
strstr (const char *s1, const char *s2)
{
  const char *p = s1;
  const size_t len = strlen (s2);

  for (; (p = strchr (p, *s2)) != 0; p++)
    {
      if (strncmp (p, s2, len) == 0)
    return (char *)p;
    }
  return (0);
}
查看更多
啃猪蹄的小仙女
3楼-- · 2019-07-31 04:39

Your code is buggy. Given:

char *haystack = "fififi-trixabelle";
char *needle = "fifi-trixabelle";

fstrset(haystack, needle) returns incorrectly returns NULL.

查看更多
Luminary・发光体
4楼-- · 2019-07-31 04:39
    char *strstr(const char *s1, const char *s2) {
      char *a = s1, *b = s2;
      for (;;)
        if      (!*b)          return (char *)s1;
        else if (!*a)          return NULL;
        else if (*a++ != *b++) {a = ++s1; b = s2;}
    }
查看更多
登录 后发表回答