C语言实现BF算法:查找字符串子串
C语言实现BF算法(暴力匹配算法)是一种简单而常见的字符串匹配算法,它通过逐个字符比较文本字符串和模式字符串来查找匹配的子串。以下是一个使用C语言实现的BF算法示例代码:
#include <stdio.h>
#include <string.h>
int main() {
char text[100], pattern[100];
int i, j, len1, len2, found;
printf("Enter the text: ");
scanf("%s", text);
printf("Enter the pattern: ");
scanf("%s", pattern);
len1 = strlen(text);
len2 = strlen(pattern);
for (i = 0; i <= len1 - len2; i++) {
found = 1;
for (j = 0; j < len2; j++) {
if (text[i + j] != pattern[j]) {
found = 0;
break;
}
}
if (found == 1) {
printf("Pattern found at position %d\n", i + 1);
}
}
if (found == 0) {
printf("Pattern not found in the text.\n");
}
return 0;
}
该代码首先获取用户输入的文本字符串和模式字符串。然后,使用两个循环遍历文本字符串中的所有可能子串,并将其与模式字符串进行比较。如果找到匹配的子串,则输出其在文本字符串中的起始位置。否则,输出未找到匹配的提示信息。
BF算法虽然简单易懂,但其效率并不高,特别是在模式字符串很长或者文本字符串包含大量重复字符的情况下。对于更复杂的字符串匹配任务,可以使用其他更高级的算法,例如KMP算法或BM算法。
原文地址: https://www.cveoy.top/t/topic/nEFS 著作权归作者所有。请勿转载和采集!