Mid$ ( string$,start[,count] )

Parameters

start - the character position to start at, counting from 1

count (optional) - how many characters to take; -1, meaning everything to the end of the string (default)

Description

Returns a piece of a string, starting at a given position.

Positions count from 1, so Mid( "hello",2,3 ) is "ell". Leave the count off and you get everything from the start position onwards: Mid( "hello",2 ) is "ello".

Mid is the workhorse of text handling. Walking a string one character at a time with Mid( s$,i,1 ) inside a For loop is how you validate input, render text into a tilemap font, or run a simple cipher. Combined with Instr it splits a line at a separator: find the separator position, then take the pieces either side.

It is forgiving at the far end. Asking for more characters than remain simply stops at the end of the string, and a start position past the end returns an empty string rather than raising an error - so you do not need to guard the tail of a loop.

The start position must be 1 or more, though. Passing 0 - easy to do if you are used to zero-based indexing - is a runtime error, not a silent shift.

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

Example

; Mid Example
; -----------

; Mid$ returns part of a string: Mid$(string$,start[,count]).
; Positions are 1-based. Leave out count to take the rest of the string.

code$="L05-W02-HARD"
Print "Level code: "+code$
Print ""

; Slice the fields out of the level code
Print "Level:      "+Mid$(code$,2,2)
Print "World:      "+Mid$(code$,6,2)
Print "Difficulty: "+Mid$(code$,9)

; Spell a name out one letter at a time
Print ""
name$="Robo"
For i=1 To Len(name$)
    Print "Letter "+i+" of "+name$+" is '"+Mid$(name$,i,1)+"'"
Next

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

End

Index