Home > Net >  Is it possible to alphabetically rearrange a String in Delphi?
Is it possible to alphabetically rearrange a String in Delphi?

Time:06-01

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'.

CodePudding user response:

Is it possible to alphabetically rearrange a string in [D]elphi[?]

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:

var A := 'strong'.ToCharArray;
TArray.Sort<Char>(A);
ShowMessage(string.Create(A));

if you only include Generics.Collections.

The first line declares a variable A. Its type is determined automatically and is TArray<Char>, that is, a dynamic array of Char (two-byte Unicode characters). The value of A is 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 A becomes '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, or string.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 Α.)

CodePudding user response:

A String can be accessed like an Array already, so you can pick every character on its own and as such also handle all of them for sorting purposes.

Bubble sort is not very efficient, but easy to program and to understand - it is named so because the sorted elements rise up from bottom to top (or left to right) like air bubbles in water would rise up:

var
  sText: String;  // Where we will sort its characters (letters)
  cTemp: Char;  // Spare place for swapping characters
  iUnsorted, iSwitch: Integer;  // Outer and inner loop
begin
  sText:= 'strong';

  // The overall sorting must be repeated as per amount of
  // characters, minus one.
  for iUnsorted:= 1 to Length( sText )- 1 do begin

    // Per sorting we compare one character with its following
    // character - that's why we need at max one iteration less
    // than the amount of characters. And per sorting iteration
    // we can ignore more and more of the text's end, because
    // all the "big" characters have been sorted there already.
    // This equals to one "bubble", carrying the biggest character
    // at the left (bottom) to the very right (top).
    for iSwitch:= 1 to Length( sText )- iUnsorted do begin

      // Is the previous character "bigger" than the next one?
      // Exchange both, so the "lower" character always comes
      // in front of the "bigger". Note that the [] syntax is
      // the same as for accessing array elements, which makes
      // the String datatype quite magic/convenient.
      if sText[iSwitch]> sText[iSwitch  1] then begin
        cTemp:= sText[iSwitch];  // Temporarily remember character
        sText[iSwitch]:= sText[iSwitch  1];  // Overwrite with other
        sText[iSwitch  1]:= cTemp;  // Replace with remembered one
      end;

      // So you see each step and how the text transforms. Just
      // add a TListBox to your form.
      Listbox1.Items.Add
      ( ' iUnsorted='  IntToStr( iUnsorted )
        ' iSwitch='  IntToStr( iSwitch )
        ' sText='  sText
      );
    end;
  end;

  // Now sText is sorted to 'gnorst'.
end;
  • Related