/*
字符串匹配算法
第二个算法:KMP匹配法
函数名:str_match
*/
#include<stdio.h>
#include<string.h>
#define MXLEN 100
/*
strs为主串,strp为模式串
若不存在匹配,则返回-1
*/
int str_match(const char* strs, const char* strp);
int main()
{
char strs[MXLEN], strp[MXLEN];
int pos;
while(scanf("%s%s", strs, strp) != EOF)
{
pos = str_match(strs, strp);
if(-1 == pos)
{
printf("No match string./n");
}
else
{
printf("match position: %d/n", pos);
}
}
return 0;
}
void get_next(int next[], const char* str)
{
int i=0, k=-1;
next[0] = -1;
while(str[i+1])
{
if(-1==k || str[i]==str[k])
{
i++, k++;
/* 假设str[i] == str[k],那么,如果对str[i]匹配失败,*/
/* 对str[k]匹配也必然是失败的,故可直接滑动到next[k] */
if(str[i] != str[k])
{
next[i] = k;
}
else
{
next[i] = next[k];
}
}
else
{
k = next[k];
}
}
return ;
}
int str_match(const char* strs, const char* strp)
{
int next[MXLEN];
int i=0; /* 指向主串下标 */
int k=0; /* 指向模式串下标 */
get_next(next, strp);
while(-1==k || strs[i] && strp[k])
{
if(-1==k || strs[i]==strp[k])
{
i++;
k++;
}
else
{
k = next[k];
}
}
if(strp[k])
{
/* 匹配失败 */
return -1;
}
return i-k;
}
字符串匹配算法
第二个算法:KMP匹配法
函数名:str_match
*/
#include<stdio.h>
#include<string.h>
#define MXLEN 100
/*
strs为主串,strp为模式串
若不存在匹配,则返回-1
*/
int str_match(const char* strs, const char* strp);
int main()
{
char strs[MXLEN], strp[MXLEN];
int pos;
while(scanf("%s%s", strs, strp) != EOF)
{
pos = str_match(strs, strp);
if(-1 == pos)
{
printf("No match string./n");
}
else
{
printf("match position: %d/n", pos);
}
}
return 0;
}
void get_next(int next[], const char* str)
{
int i=0, k=-1;
next[0] = -1;
while(str[i+1])
{
if(-1==k || str[i]==str[k])
{
i++, k++;
/* 假设str[i] == str[k],那么,如果对str[i]匹配失败,*/
/* 对str[k]匹配也必然是失败的,故可直接滑动到next[k] */
if(str[i] != str[k])
{
next[i] = k;
}
else
{
next[i] = next[k];
}
}
else
{
k = next[k];
}
}
return ;
}
int str_match(const char* strs, const char* strp)
{
int next[MXLEN];
int i=0; /* 指向主串下标 */
int k=0; /* 指向模式串下标 */
get_next(next, strp);
while(-1==k || strs[i] && strp[k])
{
if(-1==k || strs[i]==strp[k])
{
i++;
k++;
}
else
{
k = next[k];
}
}
if(strp[k])
{
/* 匹配失败 */
return -1;
}
return i-k;
}