仅代码,图解后续完善
/*
测试用例:
主串:abcdefg
子串:cde
*/
#include <stdio.h>
int BruteForce(char[] , char[]);
int main(void){
char s[10];
char t[4];
printf("请输入主串:");
scanf("%s",&s);
printf("请输入子串:");
scanf("%s",&t);
int local = BruteForce(s,t);
if(local != -1){
printf("匹配成功,位置在:%d",local);
}else{
printf("匹配失败!");
}
return 0;
}
int BruteForce(char *s , char *t){
int i , 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-j;
}else{
return -1;
}
}