Bidirectional Search
Posted: Sat Aug 11, 2007 9:09 am
Search forwards or backwards
Note that strings are passed by pointers, and the starting/returned positions by offset (0..).
It is reasonably fast (not as fast as FindString though). Assembler version (ANSI) available.
This routine is used in my MemPad
Edited: Example
To start search backwards the StartOffset must be set to the last byte of the ObjectString, or better: to Len(ObjectString)-Len(InputString).
Note: The StartOffset must be valid (i.e. not negative, and not beyond the last byte).
Note that strings are passed by pointers, and the starting/returned positions by offset (0..).
It is reasonably fast (not as fast as FindString though). Assembler version (ANSI) available.
Code: Select all
; Bidirectional Find String
; Parameters:
; *TextBase points to string to scan
; StartOffset where to start searching (0:beginning)
; *string.character points to string to find
; CharStep Ansi: 1 (forwards) or -1 (backwards)
Procedure SearchString(*TextBase,StartOffset,*string.character,CharStep)
Protected *text.character, *itext.character, *istring.character
If CharStep > 0 : CharStep = SizeOf(character)
Else : CharStep = -SizeOf(character) ; make sure correct value
EndIf
FoundOffset = -1 ; default: not found
*text = *TextBase + StartOffset ; current text pointer
While *text\c And *text >= *TextBase ; test for both directions
If *text\c = *string\c ; 1st step: scan for 1st char
*itext = *text ; if match, compare ...
*istring = *string
While *istring\c And *itext\c = *istring\c
*itext + SizeOf(character)
*istring + SizeOf(character)
Wend
If *istring\c = 0
FoundOffset = *text - *TextBase : Break
EndIf
EndIf
*text + CharStep ; plus or minus
Wend
ProcedureReturn FoundOffset ; or -1 if not found
EndProcedure
; Example:
; SearchString(@ObjectString,Len(ObjectString)-Len(InputString),@InputString,-1)
Edited: Example
To start search backwards the StartOffset must be set to the last byte of the ObjectString, or better: to Len(ObjectString)-Len(InputString).
Note: The StartOffset must be valid (i.e. not negative, and not beyond the last byte).