### Archive

Posts Tagged ‘string’

## Adding extra string manipulation techniques to BASIC

By default Sinclair BASIC provides very limited string manipulation techniques. However, you can easily add more functionality via the following methods.

The following methods are taken from an original World of Spectrum Forum thread,  started by Andrew Owen. However, I’ve added some details for better explanation of each method.

The earlier versions of UPPER\$ and LOWER\$ didn’t work as expected and Alvin Albrecht was kind enough to provide the corrected versions.

LEFT\$(string, number)

DEF FN L\$(s\$, x) = s\$( to x)

Given a string, the L\$ function will return a string starting from the leftmost character (hence called LEFT\$ in some BASIC implementations) and up to x characters to the right. Therefore, if you have a string, say “Hello” and wish to extract just “Hell” from it, you can do FN L\$(a\$, 4), where a\$ is the string holding “Hello”. A typical example in BASIC would be:

```05 DEF FN L\$(s\$, x) = s\$( to x)
10 LET a\$ = "Hello"
20 LET b\$ = FN L\$(a\$, 4)
30 PRINT b\$```

The above BASIC example is easily modified for the rest of the functions that follow.

RIGHT\$(string, number)

DEF FN R\$(s\$, x) = s\$(LEN s\$ + 1 – x TO LEN s\$)

Given a string, the R\$ function will return a string starting from the rightmost character (hence called RIGHT\$ in some BASIC implementations) and up to x characters to the left. Therefore, if you have a string, say “Hello” and wish to extract just “ello” from it, you can do FN R\$(a\$, 4), where a\$ is the string holding “Hello”.

MID\$(string, number1, number2)

DEF FN M\$(s\$, x,y) = s\$(x TO x – 1 + y)

Given a string, the M\$ function will return a string starting from anywhere in the string x and up to y characters to the right (hence called MID\$ in some BASIC implementations). Therefore, if you have a string, say “Hello” and wish to extract just “ell” from it, you can do FN M\$(a\$, 2,4), where a\$ is the string holding “Hello”.

LOWER\$(string)

DEF FN D\$(s\$) = VAL\$ “CHR\$ ((CODE s\$)+(32 AND CODE s\$ > 64 AND CODE s\$ < 92))+FN D\$(s\$(2 TO ))”( TO 27+12*(LEN s> 1))

Given a string, the D\$ function will return a string with all characters converted to lower case (hence called LOWER\$ in some BASIC implementations). Therefore, if you have a string, say “Hello” and wish to convert all of it to lower case (“hello”), you can do FN D\$(a\$), where a\$ is the string holding “Hello”.

UPPER\$(string)

DEF FN U\$(s\$) = VAL\$ “CHR\$ ((CODE s\$)-(32 AND CODE s\$ > 96 AND CODE s\$ < 124))+FN u\$(s\$(2 TO ))”( TO 28+12*(LEN s\$> 1))

Given a string, the D\$ function will return a string with all characters converted to upper case (hence called UPPER\$ in some BASIC implementations). Therefore, if you have a string, say “Hello” and wish to convert all of it to upper case (“HELLO”), you can do FN U\$(a\$), where a\$ is the string holding “Hello”.