I have two variations for sorting the characters of a string. They turn a string like "amazing" into "aagimnz". This kind of operation is frequently made to determine if two strings have the same elements irrespective of order (i.e. anagrams) and is usually performed after converting the string to all upper or lower case.
I am posting these small snippets because I think the methods used in them are interesting and unique. The methods might find some use in other areas.
One variation returns the sorted string, the other sorts the string in place. Both versions work with Ascii or Unicode and sort all characters, not just the letters. Both are faster than individually looping through the string's characters to sort them.
The subroutines take a pointer to a string and copy the string's content into the memory for a newly declared array of characters. The array is then sorted using PureBasic's SortArray(). The string is then read as a whole from the array's memory location and either returned or copied over the original strings contents. One important note is that the array's last element (an extra element) is set aside for the strings Null and is not sorted.
Code: Select all
;Author:Demivec (Jared Johnson)
;Using: PureBasic 4.31
Procedure.s sortLetters(*word.Character, wordLength) ;returns a string with the letters of a word sorted
Protected Dim letters.c(wordLength)
Protected *letAdr = @letters()
CopyMemoryString(*word, @*letAdr)
SortArray(letters(), #PB_Sort_Ascending, 0, wordLength - 1)
ProcedureReturn PeekS(@letters(), wordLength)
EndProcedure
;example
Define Before$,After$
Before$ = "demonstration"
After$ = sortLetters(@Before$,Len(Before$))
Debug Before$ + " ==> " + After$
Code: Select all
;Author:Demivec (Jared Johnson)
;Using: PureBasic v4.31
Procedure sortLettersInPlace(*word.Character, wordLength) ;sorts the letters of a word without creating a new string
Protected Dim letters.c(wordLength)
Protected *letAdr = @letters()
CopyMemoryString(*word, @*letAdr)
SortArray(letters(), #PB_Sort_Ascending, 0, wordLength - 1)
CopyMemoryString(@letters(), @*word)
EndProcedure
;example
Define Text$
Text$ = "demonstration"
Debug Text$
sortLettersInPlace(@Text$,Len(Text$))
Debug Text$