Reproduced in http://blog.csdn.net/eqmcc/article/details/8205249
Sunday.h
#include <cstdlib>#include<string>#include<iostream>#include<map>#ifndef _sundaydll_h_#define_sundaydll_h_using namespacestd;classsunday{ Public: Sunday (string&_pattern) {Pattern=_pattern; Pattern_length=pattern.size (); Match_offset=-1; } ~Sunday () {}//build the bad char table using a map, calculate the distance to move the pattern string voidBUILD_BC () { for(intI=0; i<pattern_length;++i) {Bc[pattern[i]]=pattern_length-i-1;//using a map } } voidSHOW_BC () {map<Char,int>::iterator it=Bc.begin (); while(It! =Bc.end ()) {cout<<"["<<it->first<<"]=>"<<it->second<<"\ t"<<Endl; ++it; } } intCalc_jump (inti) {Map<Char,int>::iterator it=Bc.find (Text[i]); return(It==bc.end ())?pattern_length:it->second; } voidMatchstring&_text) {Text=_text; intText_length=text.size (); inti=pattern_length-1; intpos=pattern_length-1; Match_offset=pattern_length-1; while(pos<=text_length) { while(i>=0&& Pattern[i]==text[pos]) {--i;--POS;} if(i<0) {cout<<"match at offset:"<<match_offset-pattern_length+1<<endl;return;} Else{pos=match_offset+1; intjump=Calc_jump (POS); POS=pos+Jump ; if(pos>text_length) {cout<<"no match"<<Endl;} I=pattern_length-1; Match_offset=POS; } } } Private: Map<Char,int> BC;//Bad Char map stringPattern,text; intpattern_length; intMatch_offset;};#endif/* _sundaydll_h_ */
Sunday.c
#include <cstdlib>#include<string>#include<iostream>#include"Sunday.h"intMain () {stringPattern ="Search"; stringText ="substring searching algorithm"; cout<<"Pattern:"<<pattern<<Endl; cout<<"Text:"<<text<<Endl; Sunday* Sunday =NewSunday (pattern); Sunday-BUILD_BC (); //SUNDAY->SHOW_BC ();Sunday->match (text); return 0;}