RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
TStringComparer Class

TStringComparer is a case-sensitive string comparer.

Pascal
TStringComparer = class(TCustomComparer<string>);
C++
class TStringComparer : public TCustomComparer<string>;

TStringComparer is a case-sensitive string comparer that can be used in generic collections. TStringComparer uses binary comparison and hash generation routines internally.  

Do not create instances of the TStringComparer class. TStringComparer rather acts like a singleton. Use the Ordinal method to get an instance of the TStringComparer class.  

Delphi Examples: 

 

{
This example demonstrates the usage of TComparer.
The example assumes two memos and three buttons are present on the form.
}

type
  { Declare a new custom comparer }
  TIntStringComparer = class(TComparer<String>)
  public
    function Compare(const Left, Right: String): Integer; override;
  end;

{ TIntStringComparer }

function TIntStringComparer.Compare(const Left, Right: String): Integer;
begin
  { Transform the strings into ints and perform the comparison }
  Result := StrToInt(Left) - StrToInt(Right);
end;

procedure TForm3.SortMemos(const Comparer: IComparer<String>);
var
  List: TList<String>;
  I: Integer;
begin
  { Create a new list of strings with our custom comparer }
  List := TList<String>.Create(Comparer);

  { Populate the list with numbers in the memo }
  for I := 0 to InMemo.Lines.Count - 1 do
    List.Add(InMemo.Lines[I]);

  { Sort the list }
  List.Sort();

  { Copy the list with numbers to the memo }
  OutMemo.Clear;

  for I := 0 to List.Count - 1 do
    OutMemo.Lines.Add(List[I]);

  { Free resources }
  List.Free();
end;

procedure TForm3.btCustomSortClick(Sender: TObject);
begin
  { Use our custom comparer }
  SortMemos(TIntStringComparer.Create());
end;

procedure TForm3.btDefaultSortClick(Sender: TObject);
begin
  { Use the default provided comparer }
  SortMemos(TComparer<String>.Default);
end;

procedure TForm3.btOrdinalSortClick(Sender: TObject);
begin
  { Use the ordinal string comparer }
  SortMemos(TStringComparer.Ordinal);
end;

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!