主要代码:
int BFMatch(char *s, char *p)
{
int m, n;
m = strlen(s);
n = strlen(p);
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(s[i + j] != p[j])
break;
if( j == n - 1)
{
return i;
}
}
}
return -1;
}
全部代码:
#include <stdio.h>
#include <string.h>
#include "stdlib.h"
#define MAXLEN 100
int BFMatch(char *x, char *y);
int main(int argc, char **argv)
{
char s[MAXLEN] = {"ababaababa"}; //目标串
char p[MAXLEN] = {"ababa"}; //模式串
int flag = BFMatch(s, p);
if(flag == -1)
printf("匹配失败!\n");
else
printf("匹配成功!从目标串的s[%d] = %c 处开始匹配\n", flag, s[flag]);
system("PAUSE");
return 0;
}
int BFMatch(char *s, char *p)
{
int m, n;
m = strlen(s);
n = strlen(p);
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(s[i + j] != p[j])
break;
if( j == n - 1)
{
return i;
}
}
}
return -1;
}
C++代码
#include<iostream>
#include <string.h>
#define MAXLEN 20
using namespace std;
int bf(char* a,char* b){
int al = strlen(a);
int bl = strlen(b);
for(int i = 0;i<al;i++){
for(int j =0;j<bl;j++){
if(b[j]!=a[i+j]){
break;
}
if(j == bl-1){
return i;
}
}
}
return -1;
}
int main(){
char a[MAXLEN] = {"abcddabcdd"};
char b[MAXLEN] = {"abcdd"};
int flag = bf(a,b);
if(flag == -1){
printf("匹配失败\n");
}else{
printf("字符串b匹配a[%d]值为%c",flag,a[flag]);
}
return 0;
}