首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >递归strstr函数

递归strstr函数
EN

Stack Overflow用户
提问于 2015-02-14 12:16:26
回答 2查看 1.2K关注 0票数 1

编写函数strstr,这样它将是使用以下签名的递归函数(而不是递归的包装器)。

简而言之,strstr首先返回substr出现在str中的位置的索引,如果没有找到,则返回-1。更多这里

这是我的尝试:

代码语言:javascript
复制
int strstr1(char *str, char *substr){

    if (*str == 0 || *substr == 0)//basis, if any of the strings is empty, will return -1
        return -1;
    else{
        strstr1(str + 1, substr); //forward the address of str
        if (*str == *substr)    //for each level check if the first char matches, then it should match each pair
            strstr(str + 1, substr + 1);

但我被卡住了。我意识到在递归中可能需要回溯,但我不知道如何实现,也不知道如何通过所有级别的递归来传递索引。

请问有什么提示或建议吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-14 12:57:27

"Real“strstr()返回char *(或const char *)。在C++标准中,有两个过载。为了避免链接器问题,我将strstr()重命名为strstr1()。

代码语言:javascript
复制
#include <stdio.h>
#include <string.h>

int strmatch( const char *str, const char *substr)
{
    while ( '\0' != (*substr) && (*str == *substr) )
    {
        substr++;
        str++;
    }
    if( '\0' == *substr )
        return 0;
    else
        return -1;
}

const char * strstr1( const char *str, const char* substr)
{
    printf("strstr(%s,%s)\n", str,substr );
    if( '\0' == (*str) )
        return NULL;
    if( *str == *substr )
    {
        if( 0 == strmatch( str, substr ) )
        {
            return str; // success value or something.
        }
    }
    return strstr1( str + 1, substr );
}



int main( int argc, const char * argv[] )
{
    const char * s1 = "Hello World";
    const char * ss1 = "World";

    if( NULL != strstr1( s1, ss1 ) )
    {
        printf("%s contains %s!\n", s1, ss1 );
    }
    else
    {
        printf("%s does not contain %s!\n", s1, ss1 );
    }

    const char * s2 = "Hello Universe";
    const char * ss2 = "World";

    if( NULL != strstr1( s2, ss2 ) )
    {
        printf("%s contains %s!\n", s2, ss2 );
    }
    else
    {
        printf("%s does not contain %s!\n", s2, ss2 );
    }

    const char * s3 = "Hello World World World World";
    const char * ss3 = "World";

    const char * foo = s3;
    while( NULL != foo )
    {
        foo = strstr1( foo, ss3 );
        if( NULL != foo )
        {
            puts("another match!");
            foo = foo + strlen(ss3);
        }
        else
        {
            puts("no more matches.");
        }
    }

    return 0;
}
票数 1
EN

Stack Overflow用户

发布于 2015-02-14 12:42:28

使用以下规则:如果substr是空字符串,那么查找strstr的规范以查找应该返回的内容。否则,如果str是空字符串,则返回NULL。否则,如果strcmp ( str,substr) == 0,则返回str。否则,返回strstr (str + 1,substr)。

尽管如此,这是一个非常愚蠢的递归示例,因为实际上您将使用一个循环,其中只要*str != '\0‘,就会将str增加1。

也就是说,strstr是一个标准的库函数。如果您实现一个名为strstr的函数,您将有未定义的行为。如果您实现了一个名为strstr的函数,它具有与标准库函数不同的规范,那么您的结果是DS。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28515541

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档