子串匹配 BF法

6-Tong發表於2020-12-05
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char a[202];
    char key[22];
    gets(a);
    gets(key);

    int length;
    length = strlen(key);

    int i, j;
    i = 0;
    j = 0;

    while (a[i] != '\0' && key[j] != '\0')
    {
        if (a[i] == key[j])
        {
            i++;
            j++;
        }
        else
        {
            i = i - j + 1;
            j = 0;
        }
    }

    int pos = -1;
    if (j == length)
    {
        pos = i - j;
    }

    printf("%d\n", pos);
}

相關文章