BF算法

BF算法是普通的模式匹配算法,BF算法的思想就是将目标串S的第一个字符与模式串P的第一个字符进行匹配,若相等,则继续比较S的第二个字符和P的第二个字符;若不相等,则比较S的第二个字符和P的第一个字符,依次比较下去,直到得出最后的匹配结果。

 1 //BF算法
 2 #include <iostream>
 3 
 4 using namespace std;
 5 
 6 int main(){
 7     char dst[] = "ababa";
 8     char src[] = "ababcababa";
 9     int ptr_src = 0, ptr_dst = 0, index = 0;    //index源子串在目标串中的位置 
10     int temp;
11     bool found = true;
12     cout<<sizeof(src)<<endl<<sizeof(dst)<<endl<<(sizeof(src) - sizeof(dst))<<endl;
13 
14     while(ptr_src <= (sizeof(src) - sizeof(dst))){            //遍历完目标子串  注意这儿要<=才行
15         temp = ptr_src;
16         found = true;
17         ptr_dst = 0;                                                
18 
19         //每一次的查找
20         while(ptr_dst < sizeof(dst)){
21             //如果有不相等的
22             if(src[ptr_src] != dst[ptr_dst]){
23                 found = false;
24                 break;                                    //found置为false,开始回朔
25             }
26             ptr_src++;
27             ptr_dst++;
28         }
29         if(found)                                        //查找到了
30         {
31             index = temp;
32             break;
33         }
34         ptr_src = temp + 1;
35     }
36     if(found){
37         cout<<"查找成功,首次出现的位置为:"<<index<<endl;
38     }
39     else
40         cout<<"查找失败"<<endl;
41     
42     return 0;
43 }
原文地址:https://www.cnblogs.com/luckygxf/p/4022942.html