Commodore BASIC has some interesting and simple string functions built in. Two of them are self explanatory: LEFT$ and RIGHT$. But the mysterious MID$ function is a little tricker, and I can never remember how it works.
So here’s a quick recap on how three of these work.
LEFT$ (A$,X)
The LEFT$ function takes the x left characters from a given string. Here’s an example:
a$="one-two-three" print left$(a$,3) one
We get “one”, because those are the 3 leftmost characters in our string a$.
RIGHT$ (A$,X)
Likewise, RIGHT$ takes the x right characters from any given string:
a$="one-two-three" print right$(a$,5) three
Here we get “three”, because those are the 5 right characters of a$.
MID$ (A$,X,Y)
MID$ is a little more complex. It takes x characters from a given string, starting at position y. Let’s look at our earlier example again:
a$="one-two-three" print mid$(a$,5,3) two
We get “two”, because those are the 3 characters, starting at position 5. The first position in all these string operations counts as one rather than zero.
But did you know that MID$ can also be used to assign and replace different characters in a string? Consider this:
mid$(a$,5,3)="ten" print a$ one-ten-three
Now we’ve replaced the 3 characters in our string with another string, starting at position 5.
I had no idea it cold do that! All these string operations work in all variations of the Commodore BASIC, except for the MID$ assignment which only works on the Plus/4 and the C128.