|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <string.h>
int main()
{
int BF_index(char source[], char target[]);
char source[]="abcd";
char target[]="cd";
int pos; //position
pos = BF_index( source, target);
if (-1==pos)
printf("not found!");
else
printf("the target is positioned at %d\n",pos);
return 0;
}
int BF_index(char source[], char target[]) //brute force
{
if (strlen(source) < 1 || strlen(target)<1)
return -1;
int i = 0, j = 0;
while (i < strlen(source) && j < strlen(target))
{
if (source[i] == target[j])
{
++i; // it seems there is not difference between ++i and i++
++j;
}
else
{
i = i - j + 1;
j = 0;
}
}
if(j==strlen(target))
return (i-strlen(target));
else
return -1;
}
|
|