Instr ( string$,find$[,from] )

Parameters

string - the string to search inside

find - the string to search for

from (optional) - character position to start searching from, counting from 1; 1 (default)

Description

Returns the position of one string inside another, or 0 if it is not there.

Positions count from 1, so Instr( "hello","l" ) is 3. Zero means "not found", which is why you will usually see it written as If Instr( line$,"=" ) rather than compared against anything.

The optional third value lets you carry on from where you left off. Instr( "hello","l",4 ) skips the first match and returns 4. That is the basis of splitting a line into pieces: find a separator, take the text before it with Mid, then search again starting just past the separator. Parsing a config file, a CSV level definition or a chat command all come down to this loop.

The search is case sensitive, so run both strings through Lower first if you want a case-insensitive match.

The starting position must be 1 or more - passing 0 or a negative number is an error. A starting position past the end of the string is fine and simply returns 0.

See also: Mid, Left, Right, Replace, Len.

Example

; Instr Example
; -------------

; Instr returns the position of a substring inside a string (1-based),
; or 0 if it is not there. An optional third parameter sets where the
; search starts - useful for finding repeated matches.

save$="name=Robo;score=1250;level=7"
Print "Save-file line: "+save$
Print ""

; Find the first '=' sign
p=Instr(save$,"=")
Print "First '=' is at position "+p

; Search again, starting just past the first match
p2=Instr(save$,"=",p+1)
Print "Next '=' is at position "+p2

; A quick chat-command check
chat$="/whisper Robo meet me at the gate"
If Instr(chat$,"/whisper")=1 Then Print "Chat line starts with the /whisper command"

; A failed search returns 0
Print "Searching for 'lives' returns "+Instr(save$,"lives")

Print ""
Print "Press any key to close the example"
WaitKey

End

Index