User Tools

Site Tools


Sorting the characters in a string

by Richard Russell, October 2008

You can quickly and easily sort the elements of an array by using the SORTLIB library, but BBC BASIC for Windows does not directly provide the facility to sort the characters in a string. The code listed below allows you to do that.

First you should initialise SORTLIB in the usual way, just once at the start of your program:

        INSTALL @lib$+"SORTLIB"
        Sort% = FN_sortinit(0,0)

Change the parameters of FN_sortinit if necessary, as explained here.

The following function sorts a string into an ascending (or descending) sequence of characters:

        DEF FNsortstring(A$)
        LOCAL C%, A&()
        C% = LEN(A$)
        DIM A&(C%)
        $$^A&(0) = A$
        CALL Sort%, A&(0)
        = $$^A&(0)

This works by temporarily creating a byte array, copying the string into the array, sorting the byte array, and finally returning the contents of the array as a string.

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
sorting_20the_20characters_20in_20a_20string.txt · Last modified: 2018/04/17 19:52 by tbest3112