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:

code format="bb4w" INSTALL @lib$+"SORTLIB" Sort% = FN_sortinit(0,0) code 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:

code format="bb4w" DEF FNsortstring(A$) LOCAL C%, A& C% = LEN(A$) DIM A&(C%) $$^A&(0) = A$     CALL Sort%, A&(0) = $$^A&(0) code 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.