/***********************************************************
sboymoo.c -- Boyer--Moore法
***********************************************************/
/* 簡略Boyer-Moore法 */
Const UCHAR_MAX= 255
Function position(text As *Byte, pattern As *Byte) As Long
Dim i As Long, j As Long, k As Long, len As Long
Dim skip[UCHAR_MAX] As Long
Dim c As Byte, tail As Byte
len = lstrlen(pattern) /* 文字列の長さ */
If len = 0 Then *NOT_FOUND /* エラー: 長さ0 */
tail = pattern[len - 1] /* 最後の文字 */
If len = 1 Then
i = 0 /* 長さ1なら簡単! */
While text[i] <> 0
If text[i] = tail Then
position =i
Exit Function
End If
i++
Wend
Else /* 長さ2以上なら表を作って… */
For i = 0 To UCHAR_MAX: skip[i] = len: Next
For i = 0 To len - 2
skip[pattern[i]] = len - 1 - i
Next
/* i = len - 1; */ /* いよいよ照合 */
c = text[i]
While c <> 0
If c = tail Then
j = len - 1: k = i
j--: k--
while (pattern[j] = text[k])
if (j = 0) Then /* 見つかった */
position =k
Exit Function
End If
j--: k--
Wend
End If
i = i + skip[c]
c = text[i]
Wend
End If
*NOT_FOUND
position = -1 /* 見つからなかった */
End Function
#N88BASIC
Dim i As Long
Dim text = "私の名前は平井公彦" As *Byte
Dim pattern[3] = ["私の", "名前は", "平井公彦", "阿部高和"] As *Byte
Dim out[100] As Byte
For i=0 To 3
wsprintf(out, Ex"position(\q%s\q, \q%s\q) = %d\n",
text, pattern[i], position(text, pattern[i]))
Print MakeStr(out)
Next