#include
<
stdio.h
>
#include < stdlib.h >
#define MAX 255
void get_next( const char * T, int * next) // 算法4.7
{
int i = 0 ,j =- 1 ;
next[ 0 ] =- 1 ;
while (i < strlen(T)) {
if (j ==- 1 || T[i] == T[j]) {
++ i; ++ j; next[i] = j;
}
else j = next[j];
}
}
int Index_KMP( const char * S, const char * T) { // 算法4.6
int * next = ( int * )malloc( sizeof ( int ) * strlen(T));
int i = 0 , j = 0 ;
get_next(T, next);
while (i < strlen(S) && j < strlen(T))
{
if (j == - 1 || S[i] == T[j]) {
++ i; ++ j;
}
else j = next[j];
}
if (j >= strlen(T)) return i - strlen(T);
else return 0 ;
}
/*
int Index (char S[], char T[]) //模式匹配算法
{
int i=0;
int j=0;
while (S[i]!='/0'&&T[j]!='/0')
{
if (S[i]==T[j]) {++i;++j;}
else {i = i-j+1;j=0;}
}
if ( T[j]=='/0') return i-strlen(T);
else return 0;
}
*/
void main() // 主函数
{
char str1[MAX];
char str2[MAX];
int position = 0 ;
int i,j;
int l;
printf( " 请输第一个字符串: " );
gets(str1);
printf( " 请输第二个字符串: " );
gets(str2);
l = strlen(str2);
position = Index_KMP(str1, str2);
// position=Index(str1,str2) ;
if (position == 0 )
printf( " 没有匹配! " );
else
{
for (i = 0 ;i < position;i ++ ) {str2[i] = str1[i];}
j = i + l;
while (str1[j] != '/ 0 ' )
{str2[i] = str1[j]; i ++ ; j ++ ;}
str2[i] = ' /0 ' ;
printf( " 结果为:%s " ,str2);
}
}
#include < stdlib.h >
#define MAX 255
void get_next( const char * T, int * next) // 算法4.7
{
int i = 0 ,j =- 1 ;
next[ 0 ] =- 1 ;
while (i < strlen(T)) {
if (j ==- 1 || T[i] == T[j]) {
++ i; ++ j; next[i] = j;
}
else j = next[j];
}
}
int Index_KMP( const char * S, const char * T) { // 算法4.6
int * next = ( int * )malloc( sizeof ( int ) * strlen(T));
int i = 0 , j = 0 ;
get_next(T, next);
while (i < strlen(S) && j < strlen(T))
{
if (j == - 1 || S[i] == T[j]) {
++ i; ++ j;
}
else j = next[j];
}
if (j >= strlen(T)) return i - strlen(T);
else return 0 ;
}
/*
int Index (char S[], char T[]) //模式匹配算法
{
int i=0;
int j=0;
while (S[i]!='/0'&&T[j]!='/0')
{
if (S[i]==T[j]) {++i;++j;}
else {i = i-j+1;j=0;}
}
if ( T[j]=='/0') return i-strlen(T);
else return 0;
}
*/
void main() // 主函数
{
char str1[MAX];
char str2[MAX];
int position = 0 ;
int i,j;
int l;
printf( " 请输第一个字符串: " );
gets(str1);
printf( " 请输第二个字符串: " );
gets(str2);
l = strlen(str2);
position = Index_KMP(str1, str2);
// position=Index(str1,str2) ;
if (position == 0 )
printf( " 没有匹配! " );
else
{
for (i = 0 ;i < position;i ++ ) {str2[i] = str1[i];}
j = i + l;
while (str1[j] != '/ 0 ' )
{str2[i] = str1[j]; i ++ ; j ++ ;}
str2[i] = ' /0 ' ;
printf( " 结果为:%s " ,str2);
}
}