繁体   English   中英

递归strstr函数

[英]Recursive strstr function

使用以下签名编写函数strstr ,使其成为递归函数(而不是用于递归的包装器)。

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

这是我的尝试:

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);

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

有什么提示或建议吗?

“ Real” strstr()返回一个char *(或const char *)。 在C ++标准中,有2个重载。 为避免链接程序问题,我将strstr()重命名为strstr1()。

#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;
}

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

也就是说,这是一个相当愚蠢的递归示例,因为实际上您会使用一个循环,只要* str!='\\ 0',就可以将str增加1。

也就是说,strstr是标准库函数。 如果实现名为strstr的函数,则将具有未定义的行为。 如果实现的strstr函数的规格与标准库函数的规范不同,则最终会进入DS。

暂无
暂无

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

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