蛮力字符串匹配

时间:2021-06-20 06:12:01
 
//BruteForceStringMatch

#include <stdio.h>
#define N 4
#define M 19


int BruteForceStringMatch(char T[M], char P[N]);

int main()
{
    int n;
    char T[M] = {"NOBODY_NOTICED_HIM"};
    char P[N] = {"NOT"};

    n = BruteForceStringMatch(T,P);
    
    if (n < 0)
    {
        printf("没有匹配的字符串");
    }
    else
    {
        printf("成功查询到字符串从%d个字符开始\n",n+1);
    }
    printf("\n");
    return 0;
}

int BruteForceStringMatch(char T[M], char P[N])
{
    int i,j;
    for (i = 0; i < M - N; i++)
    {
        j = 0;
        while(j < N && P[j] == T[i+j])
        {
            j++;
        }
        if (j == N-1)
        return i;
    }
    return -1;
}