求得是匹配的次数而不是匹配的位置
时间: 2024-02-17 14:04:14 浏览: 27
如果需要求匹配的次数,可以在`kmp_match`函数中增加一个计数器,记录匹配的次数,然后在函数结束时返回该计数器的值。修改后的代码如下:
```c
#include <stdio.h>
#include <string.h>
void get_next(char *pattern, int *next) {
int i = 0, j = -1;
int len = strlen(pattern);
next[0] = -1;
while (i < len) {
if (j == -1 || pattern[i] == pattern[j]) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
}
int kmp_match(char *text, char *pattern) {
int i = 0, j = 0;
int len1 = strlen(text);
int len2 = strlen(pattern);
int next[100];
get_next(pattern, next);
int count = 0; // 计数器
while (i < len1 && j < len2) {
if (j == -1 || text[i] == pattern[j]) {
i++;
j++;
} else {
j = next[j];
}
count++; // 匹配次数加1
}
if (j == len2) {
return count; // 匹配成功,返回匹配次数
} else {
return 0; // 匹配失败,返回0
}
}
int main() {
char text[100], pattern[100];
printf("请输入主串:");
scanf("%s", text);
printf("请输入子串:");
scanf("%s", pattern);
int result = kmp_match(text, pattern);
if (result) {
printf("匹配成功,匹配次数为:%d\n", result);
} else {
printf("匹配失败\n");
}
return 0;
}
```
现在调用`kmp_match`函数返回的是匹配的次数,根据返回结果输出即可。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)