User Tools

Site Tools


Reversing a string

by Jon Ripley, May 2006

Reversing is a simple string manipulation that often has a sub-optimal solution.

One commonly used method to reverse strings is:

        a$="Hello world!"
        IF LEN(a$)>0 THEN
          FOR i%=0 TO l% DIV 2
          NEXT i%
        PRINT a$

This method using the built in string function MID$( four times and requiring one temporary variable t$ can be made approximately 4 times faster by improving the algorithm used.

It might seem logical to use the SWAP command to exchange the characters in the string, however the following code is a syntax error:

        SWAP MID$(a$,i%,1),MID$(a$,l%-i%,1)

The BBC BASIC manual tells us that SWAP can exchange the contents of two locations in memory, if we know the address of the string we can manipulate the string directly in memory. To do this use the pointer operator ^ to locate the address of the string in memory. The address in memory of any$ is ^any$. The address of the text stored in any$ is !^any$.

We can use this information to create the following optimal code to reverse a string:

        a$="Hello world!"
        IF a$>"" THEN
          FOR i%=0 TO l% DIV 2
            SWAP p%?i%, l%?(p%-i%)
          NEXT i%
        PRINT a$

Here we loop through the first half of the string and swap the characters with those in the second half of the string.

This algorithm can be made significantly faster by rewriting it in assembly language.

This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
reversing_20a_20string.txt · Last modified: 2018/04/17 19:33 by tbest3112