From Liberty BASIC Family
Jump to navigation Jump to search
Supported in Just BASIC Supported in Liberty BASIC Not supported in Liberty BASIC 5 Not supported in Run BASIC


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.
See also LEFT$() and RIGHT$().


  1. mid$(string, index, [number])


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.


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);
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 "String "; CHR$(34); String$; CHR$(34); " is "; Length; " Characters long"

' 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)

' terminate the program

Useful Procedures

'Converts number to hexadecimal string. So, 255->"FF"
Function hex$(n)
    h$ = ""
        h$ = mid$("0123456789ABCDEF", (n mod 16)+1, 1) + h$
        n = int(n/16)
    loop while n > 0
    hex$ = h$
End Function