Backtracking:
Const char * mystrstr (const char * Text, const char * pattern)
2 {
3 int I = 0, j = 0;
4
5 while (pattern [I] & text [J])
6 {
7 if (pattern [I] = text [J])
8 {
9 + + I;
10 + + J;
11}
12 else
13 {
14 I = 0;
15 J = J-I + 1;
16}
17} // while
18
19 if (! Pattern [I])
20 {
21 return text + J-I;
22}
23 else
24 {
25 return 0;
26}
27}
No backtracking:
# Include <cstring>
2 int BM (const char * Text, const char * pattern)
3 {
4 int arrshifttable [256];
5 Int tlen = strlen (text );
6 int Plen = strlen (pattern );
7 int currpos, treadpos, preadpos;
8
9 // exclude NUL
10 For (INT I = 1; I <sizeof arrshifttable/sizeof (INT); I ++)
11 {
12 arrshifttable [I] = Plen;
13}
14
15 // exclude the last char in Pattern
16 For (INT I = 0; I <Plen-1; I ++)
17 {
18 arrshifttable [pattern [I] = Plen-1-I;
19}
20
21 For (currpos = Plen-1; currpos <tlen;/** // * null */)
22 {
23 For (preadpos = Plen-1, treadpos = currpos;
24 preadpos> = 0 & pattern [preadpos] = text [treadpos];
25 preadpos --, treadpos --)
26/** // * null */;
27
28 If (preadpos <0)
29 {
30 return treadpos + 1;
31}
32 else
33 {
34 currpos + = arrshifttable [Text [currpos];
35}
36
37} // outer
38
39 return-1;
40}