gpt4 book ai didi

检查子串是否在主串中,如果是,从找到的子串开始打印主串

转载 作者:太空宇宙 更新时间:2023-11-03 23:45:23 25 4
gpt4 key购买 nike

我有一个获取 2 个字符串的代码,它必须检查主字符串是否包含子字符串,如果包含,它将打印主字符串,但它将从子字符串的位置开始。例如,如果我的主字符串是“hello my name is”,而我的子字符串是“my”,它将打印“my name is”作为新的主字符串。

我有代码,它正在运行。但我很难理解它为什么起作用。谁能解释一下这个功能是如何工作的?

char *recursiveStrStr(char *str, char *substr);

尤其是这一行:

return recursiveStrStr(str + 1, substr);

这是代码:

#include <stdio.h>
#include <conio.h>

int recursiveHasPrefix(char *str, char *prefix);
char *recursiveStrStr(char *str, char *substr);

int main()
{

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);
}
getch();
return 0;
}

int recursiveHasPrefix(char *str, char *prefix)
{
if (*prefix == '\0')
return 1;
if (str[0] != prefix[0])
return 0;
return recursiveHasPrefix(str + 1, prefix + 1);

}

char *recursiveStrStr(char *str, char *substr)
{
int check;
if (*str == '\0' && *substr != '\0')
return 0;

check = recursiveHasPrefix(str, substr);
if (check == 1)
return str;

return recursiveStrStr(str + 1, substr);

}

最佳答案

ABCDEFG CDEF

输出:CDEFG

Now what your program doing?

ABCDEFG CDEF ---> Is there any common prefix such that it's length=len(CDEF)=4
No so return 0

BCDEFG CDEF --> No

CDEFG CDEF --> matches ...then go to DEFG DEF ---> EFG EF --> FG F --> G . return 1.

现在你正在返回那个点并打印。

关于检查子串是否在主串中,如果是,从找到的子串开始打印主串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34702931/

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