gpt4 book ai didi

c - 递归 strstr 函数

转载 作者:太空宇宙 更新时间:2023-11-04 04:38:48 24 4
gpt4 key购买 nike

Write the function strstr such that it would be a recursive function (not a wrapper for recursion) using the following signature.

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

这是我的尝试:

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

关于c - 递归 strstr 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28515541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com