繁体   English   中英

c中的递归strstr函数

[英]recursive strstr function in c

我写了我的递归 strstr 但问题是,如果我有这个代码:

char *str = "Yesterday all my troubles seemed so far away";
char *subStr[6] = { "Yes", "all", "my", "see", "far", "day" };
char *res;
int i;
printf("%s\n", str);
res = str;
for (i = 0; i<6; i++)
{
    printf("%s\n", subStr[i]);
    res = recursiveStrStr(res, subStr[i]);
    if (res == 0)
    {
        printf("The specified text is not found.\n");
        break;
    }
    else
        printf("The found text: %s\n", res);
}

我的 strstr 返回 str 非常好,直到它到达 i=5 所以 substr 是“day”,左边的 str 是“很远”,它应该返回 0 - 这意味着找不到文本但它返回 str 不明白为什么?

我的 strstr 代码(应该是递归的):

int recursiveStrStr(char * str, char *substr)
{

    if (str == NULL  )
        return 0;
    else if (strncmp(str, substr, strlen(substr)) == 0)
        return str;
    else 
        return(recursiveStrStr(str+1, substr));

}

也可以编写递归 strstr 而不调用任何其他函数,但 strstr 本身:

char *RecStrStr(const char *haystack, const char *needle)
{
    assert(haystack);
    assert(needle);

    if(*needle == 0)
        return (char *)haystack;

    if(*haystack == 0)
        return NULL;

    if(*haystack == *needle &&
        RecStrStr(haystack + 1, needle + 1) == haystack + 1)
        return (char *)haystack;

    return RecStrStr(haystack + 1, needle);
}

基本上,有两种类型的递归调用:

  1. Needle 和 haystack 当前字符匹配,在这种情况下,您将推进两个指针以比较下一个字符。
  2. 针的当前字符与干草堆的当前字符不匹配,在这种情况下,您只能前进干草堆的位置。

如果到达空终止,那是因为needle不是haystack的子串,返回NULL。

如果达到了needle的空终止,那是因为haystack和needle连续匹配,返回一个指向当前haystack位置的指针。

为什么? 这就是事情变得有点复杂的地方 - 为了在针是 haystack 的非连续子串时不返回肯定的答案,我们需要确保下一个匹配的返回值是当前跟随的指针(这是第三个 if 中的第二个条件。

如果needle 确实是haystack 的一个子串,则返回值将是匹配开始的指针,根据需要。

我想它应该是(*str == NULL)

您需要另一个子句来返回“未找到”。

if ( *str == '\0' )
   return NULL;

没有它,你会一直增加str直到你访问越界内存。

另外,我会将函数的返回类型更改为char*

char* recursiveStrStr(char * str, char *substr)
{
   if (str == NULL  )
      return NULL;

   if ( *str == '\0' )
      return NULL;

   if (strncmp(str, substr, strlen(substr)) == 0)
      return str;

   return(recursiveStrStr(str+1, substr));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM