C语言 strstr() 函数的实现

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3557178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:17:39  来源:igfitidea点击:

implementation of strstr() function

c

提问by fuddin

The code says at many places "invalid indirection".Please help.

代码在很多地方都说“无效的间接寻址”。请帮忙。

   int main()
    {

        char *s1,*s2,*position;
        printf("Enter string:\n");
        gets(s1);
        printf("Enter word to find:\n");
        gets(s2);
        *position=ststr(*s1,*s1);
        if(*position)
        printf("word is found at %c loc\n",*position);
        else
        printf("word not found");
        getch();
        return 0;

    }

char *strstr(char *s1,char *s2)
{
    int flag=1;
    char i,j;
    for(i=0; ;i++)
    {
        if(*s1[i]==*s2[0])
        for(j=i;*s2;j++)
        {
            if(*s1[j]!=*s2[j])
            flag=0;
        }

    }
    if(flag)
    return i;
    else
    return 0;
}

回答by John Bode

First, s1and s2in main have not been initialized to point anywhere meaningful. Either declare them as static arrays, or allocate memory to them at runtime using malloc()or calloc():

首先,s1s2在主还没有被初始化为指向任何地方有意义。要么将它们声明为静态数组,要么在运行时使用malloc()or为它们分配内存calloc()

#define SIZE 20 // or some number big enough to hold your input
...
char s1[SIZE], s2[SIZE], *position; // s1 and s2 declared statically

Second, NEVER NEVER NEVER NEVER NEVERuse gets(); it willintroduce a point of failure in your program. Use fgets()instead:

其次,永远永远永远永远永远永远不要使用gets(); 它在您的程序中引入一个故障点。使用fgets()来代替:

if (fgets(s1, sizeof s1, stdin) != NULL)
  // process s1
else
  // check for EOF or error on read

EDIT

编辑

And like everyone else has pointed out, your comparison in the strstr()function needs to be either

就像其他人指出的那样,您在strstr()函数中的比较需要是

*s1 == *s2

or

或者

s1[i] == s2[i]

but first you need to deal with allocating your buffers in main properly.

但首先您需要处理在 main 中正确分配缓冲区的问题。

回答by user3233434

#include "stdio.h"
char *strstr(char *str, char *substr)
{
    int len = strlen(substr);
    char *ref = substr;
    while(*str && *ref)
    {
        if (*str++ == *ref)
        {
            ref++;
        }
        if(!*ref)
        {
            return (str - len);
        }
        if (len == (ref - substr))
        {
            ref = substr;
        }
    }
    return NULL;
}

int main(int argc, char *argv[])
{
  printf("%s \n", strstr("TEST IS NOT DONE", "IS NOT"));
}

回答by Andre Holzner

if(*s1[i]==*s2[0])

is such an example where my gcc complains:

就是这样一个例子,我的 gcc 抱怨:

error: invalid type argument of ‘unary *' (have ‘int')

if s1is a pointer to char, s1[i]is a char. So you can't dereferenceit any more (with the *), i.e. s1[i]does not point to anything any more.

ifs1是指向 的指针chars1[i]是一个字符。所以你不能再使用dereference它了(用*),即s1[i]不再指向任何东西。

Try

尝试

if(s1[i]==s2[0])

instead.

反而。



You should also change the return value of strstr: you return an integer where you declare to return a pointer to a character. So try returning s1+iinstead.

您还应该更改的返回值strstr:您返回一个整数,您声明返回一个指向字符的指针。所以尝试返回s1+i



This here:

这里:

for(j=i;*s2;j++)

probably does not what you want. You're not advancing the pointer s2anywhere in the loop, in fact you're just testing whether s2[0](which is the same as *s2) is zero for each iteration. If s2isn't the empty string, this loop will never terminate.

可能不是你想要的。您没有s2在循环中的任何位置推进指针,实际上您只是在测试每次迭代s2[0](与 相同*s2)是否为零。如果s2不是空字符串,则此循环将永远不会终止。

回答by KLee1

One of the problems I'm noticing is whenever you do *s1[j]. The asterisk is dereferencing the array, and so is the []notation.

我注意到的问题之一是每当您这样做时*s1[j]。星号正在取消引用数组,[]符号也是如此。

s[i]really means *(s + i), so you don't have to dereference it again. The way you have it would read **(s + i), and since it's a single pointer you can't do that.

s[i]真的意味着*(s + i),所以你不必再次取消引用它。你拥有它的方式会读取**(s + i),因为它是一个单一的指针,你不能这样做。

回答by James Curran

         if(*s1[j]!=*s2[j]) 
  • *s1means "the character where s1 is pointing".
  • s1[j]means "*(s1+j)" or "the character j positions after where s1 is pointing"
  • *s1意思是“s1 指向的字符”。
  • s1[j]表示“ *(s1+j)”或“字符 j 位于 s1 指向的位置之后”

You have to use one or the other; not both.

您必须使用其中之一;不是都。

回答by Pradeep

#include <stdio.h>

char* my_strstr(char *s2, char *s1)
{
  int i, j;
  int flag = 0;

  if ((s2 == NULL || s1 == NULL)) return NULL;

  for( i = 0; s2[i] != '##代码##'; i++)
  {
    if (s2[i] == s1[0])
    {
      for (j = i; ; j++)
      {
        if (s1[j-i] == '##代码##'){ flag = 1; break;}
        if (s2[j] == s1[j-i]) continue;
        else break;
      }
    }
    if (flag == 1) break;
  }

  if (flag) return (s2+i);
  else return NULL;
}

int main()
{
  char s2[] = "This is the statement";
  char s1[] = "the";
  char *temp;

  temp = my_strstr(s2,s1);

  printf("%s\n",temp);
  return 0;
}