MID$()
Jump to navigation
Jump to search
Description
- Beginning at the index position, extracts and returns characters from a string. Returns all characters from index to the end of string, if optional number is NOT specified.
Syntax
- mid$(string, index, [number])
Hints
- index starts from 1. (well, for BASIC this is expected).
- If number is specified, then the specified number of characters is returned, starting at index.
- mid$(a$, i, 1) means "i-th letter of a$", and often used to pick letters in a loop one by one.
- If the range enclosed by index and number does not overlap the size of the string, an empty string will be returned.
Example
General Usage
a$="Just BASIC is awesome" print len(a$) '21, for our convenience '5 letters starting from letter 6, prints >BASIC< print ">";mid$(a$, 6, 5);"<" 'letters starting from letter 12 to the end, prints >is awesome< print ">";mid$(a$, 12);"<" 'mid$(a$, i, 1) means "i-th letter of a$", and often used to pick letters in a loop one by one 'For example, Just BASIC reversed: a$="Just BASIC" print ">"; for i=len(a$) to 1 step -1 print mid$(a$, i, 1); next print "<" 'prints >CISAB tsuJ<
Moving a range over a string
' define the string String$ = "Just BASIC" ' get the length of the string Length = LEN(String$) ' calculate the starting position of the range StartPos = 1 - Length ' calculate the ending position of the range EndPos = Length + 1 ' print a header PRINT PRINT "String "; CHR$(34); String$; CHR$(34); " is "; Length; " Characters long" PRINT ' display the resulting substring from the ranges FOR i = StartPos to EndPos PRINT "Start "; USING("####", i), _ "End "; USING("####", i + Length - 1), _ MID$(String$, i, Length) NEXT ' terminate the program END
Useful Procedures
'Converts number to hexadecimal string. So, 255->"FF" Function hex$(n) h$ = "" do h$ = mid$("0123456789ABCDEF", (n mod 16)+1, 1) + h$ n = int(n/16) loop while n > 0 hex$ = h$ End Function