在str中找ttr第一次出现的位置,没找到就是-1,

bf算法暴力匹配

int BF(char s[], char p[])
{
    int m, n,i,j;
    m = strlen(s);
    n = strlen(p);
    for(i = 0; i < m; i++)
    {
        for(j = 0; j < n; j++)
        {
            if(s[i + j] != p[j])
                break;
            if( j == n - 1)
            {
                return i;
            }
        }
    }
    return -1;
}

kmp算法FJUTACM2149
#include<stdio.h>
#include<string.h>
char s1[1000005],s2[1000005];
int next[1000005];
void get_next(char s[])///求next数组
{
    int i=0,j=-1;
    next[0]=-1;     ///虽然while第一次填next[0]=-1,但是去掉会死循环
    int len=strlen(s);
    while(i<len)
    {
        if(j==-1||s[i]==s[j])
        {
            i++;
            j++;
            ///特例优化 aaaaab 匹配aaaaax时b-x匹配失败,回溯
            if(s[i]!=s[j])
            {
                next[i]=j;
            }
            else
            {
                next[i]=next[j];
            }
        }
        else
        {
            j=next[j];
        }
    }
}
int kmp(char *str,char *ttr)
{
    int i=0,j=0;
    int len1=strlen(str),len2=strlen(ttr);///strlen返回值unsigned放在while会出错
    while(i<len1&&j<len2)
    {
        if(j==-1||str[i]==ttr[j])
        {
            i++;
            j++;
        }
        else
        {
            j=next[j];
        }
    }
    if(j==len2)///succeed
    {
        return i-j;
    }
    else///failed
        return -1;
}
int main()
{
    while(~scanf("%s%s",s1,s2))
    {
        memset(next,0,sizeof(next));
        get_next(s2);
        printf("%d\n",kmp(s1,s2));
    }
    return 0;
}