检查主字符串中是否有子字符串,如果是,则从找到的子字符串的开头打印主字符串

时间:2016-01-10 07:00:41

标签: c arrays

我有一个获得2个字符串的代码,它必须检查主字符串是否包含子字符串,如果是,它将打印主字符串,但它将从子字符串&#39开始的位置。例如,如果我的主要字符串是"你好,我的名字是",而我的子字符串是"我的",它将打印"我的名字是"作为新的主要字符串。

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

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

}

1 个答案:

答案 0 :(得分:1)

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.

现在你要返回那一点并打印。