I have seen many things on how to sort Strings in an Array alphabetically. I was wondering if it possible to take an individual String (for example just a single word you entered through a TEdit) and rearrange the string so it's in alphabetical order. For example:
- you would take the word
'strong', - which would be rearranged to
'gnorst'.
This is a slightly strange question, because its answer is trivially "Yes, of course".
Also, if you have a basic understanding of Delphi strings and sorting algorithms, implementing this isn't difficult. So a grumpy Stack Overflow user may ask you to simply learn these two subjects separately, and then use the combined knowledge to solve the task.
However, perhaps the actual question is instead, "Is there a canonical (or simple) way to do this in modern Delphi versions?"
If so, the question becomes more interesting, and actually very answerable:
if you only include
Generics.Collections.The first line declares a variable
A. Its type is determined automatically and isTArray<Char>, that is, a dynamic array ofChar(two-byte Unicode characters). The value ofAis simply the array of characters of the string:'s', 't', 'r', 'o', 'n', 'g'.The second line sorts this array using the default comparer. Thus
Abecomes'g', 'n', 'o', 'r', 's', 't'. You may use an overloaded method to specify a different comparer which takes into account the current locale, for instance.¹The third line creates a new string from this character array,
'gnorst', and displays it in a message box.A decade or two ago, there were no
string.ToCharArray,TArray, orstring.Create. But of course you could manually (and easily) obtain a character array from a string, sort this using the methods you learned in Computer Science 101, and then create a new string from this array. Or, if you wanted to be smart, you could do this in-place in the string heap object.¹ Actually, sorting "alphabetically" is much more involved than you may think. For instance, how do you sort "aAÅÄäåáÀ☃4ΑÄãâĀ"? Will the result be the same in Sweden and in Germany? Also please note the difference between Ä and Ä and between A and Α.)