String Operations on Commodore Computers

- by

Commodore BASIC has some interesting and simple string functions built in. Three of them are self explanatory: LEN, LEFT$ and RIGHT$. But others, like the mysterious MID$ and INSTR functions, are a little tricker, and I can never remember how they works.

So here’s a quick recap on how they all work.

LEN (A$)

Returns the length of any given string. For example,

a$=”the cake is a lie”

print len (a$)
17

returns 17, which is the number of characters in our string.

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.

 

INSTR (A$, B$)

On the Plus/4 and C128, we can even check if one string is contained in another and at which position this occurs. Consider this:

a$="the cake is a lie"

b$="cake"

print instr(a$,b$)
 5

In our example, INSTR returns 5 because “cake” has been found at position 5 of “the cake is a lie”.

We can also specify a position from which the search shall be started like this:

print instr(a$,b$,6)
 0

Now INSTR returns 0 because “cake” has not been found beyond position 6 of our input string.



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.