使用C语言的kmp算法匹配字符串
时间: 2024-05-15 22:19:32 浏览: 16
以下是使用C语言实现KMP算法匹配字符串的代码:
```c
#include <stdio.h>
#include <string.h>
void get_next(char *pattern, int *next)
{
int i = 0, j = -1;
next[0] = -1;
while (i < strlen(pattern)) {
if (j == -1 || pattern[i] == pattern[j]) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
}
int kmp(char *text, char *pattern)
{
int i = 0, j = 0;
int next[strlen(pattern)];
get_next(pattern, next);
while (i < strlen(text) && j < strlen(pattern)) {
if (j == -1 || text[i] == pattern[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == strlen(pattern)) {
return i - j;
} else {
return -1;
}
}
int main()
{
char text[] = "hello world";
char pattern[] = "world";
int index = kmp(text, pattern);
if (index != -1) {
printf("Match found at index %d\n", index);
} else {
printf("Match not found\n");
}
return 0;
}
```
在这个例子中,我们将文本字符串设置为“hello world”,要查找的模式字符串为“world”。在主函数中,我们调用kmp函数来匹配这两个字符串。如果匹配成功,函数返回匹配的索引位置,否则返回-1。在本例中,输出为“Match found at index 6”,表示匹配成功,并且从索引位置6开始找到了匹配的字符串。