我使用以下KMP算法代码进行字符串匹配。它可以很好地搜索字符串中的给定模式。
/*
* C Program to Implement the KMP Pattern Searching Algorithm
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char string[100], matchcase[20], c;
int i = 0, j = 0, index;
printf("Declertion and Initialization done:\n");
/*Scanning string*/
printf("Enter string:");
do
{
fflush(stdin);
c = getchar();
string[i++] = tolower(c);
} while (c != '\n');
string[i - 1] = '\0';
printf("The string after scanning is:%s\n",string);
printf("String length of string is: %d\n",strlen(string));
/*Scanning substring*/
printf("Enter substring: ");
i = 0;
do
{
fflush(stdin);
c = getchar();
matchcase[i++] = tolower(c);
} while (c != '\n');
matchcase[i - 1] = '\0';
for (i = 0; i < strlen(string) - strlen(matchcase) + 1; i++)
{
index = i;
if (string[i] == matchcase[j])
{
do
{
i++;
j++;
} while(j != strlen(matchcase) && string[i] == matchcase[j]);
if (j == strlen(matchcase))
{
printf("Match found from position %d to %d.\n", index + 1, i);
return 0;
}
else
{
i = index + 1;
j = 0;
}
}
}
printf("No substring match found in the string.\n");
return 0;
}
它成功搜索模式,仅给出第一个匹配,但是,我有兴趣报告所有匹配。感谢