尝试按照自己的理解来进行串模式的匹配

思路

大致是按照循环从主串第一个字符和模式串第一个字符比较,相同就进入比较各位的循环,若存在不同就返回到开始进行比较的后一位,继续与模式串第一个字符比较

#include<stdio.h>
#include<string.h>
int compare_f(char *S, char *P);
int main(void)
{
    char S[100], P[100];
    printf("请输入模式串:");
    scanf("%s", P);
    printf("请输入主串:");
    scanf("%s", S);
    int n = compare_f(S, P);
    if(n)
        printf("right! the string you want to find is at %d of the main string!", n);
    return 1;
}

int compare_f(char *S, char *P)
{
    if(strlen(S) < strlen(P))
        return 0;
    for (int i = 0; S[i]; i++)
    {
        if(S[i] == P[0])
        {
            int j = i + 1, k = 1;
            for (; P[k]; k++, j++)
            {
                if(S[j] != P[k])
                    break;
            }
            if(k == strlen(P))
                return i + 1;
        }
    }
    return 0;
}

运行结果

请输入模式串:abc
请输入主串:ababcaabc
right! the string you want to find is at 3 of the main string!
请输入模式串:abc
请输入主串:aabbabbcabc
right! the string you want to find is at 9 of the main string!
最后修改:2021 年 10 月 09 日
如果觉得我的文章对你有用,请随意赞赏