如何按长度排序字符串数组?

时间:2017-12-30 09:39:28

标签: arrays sorting delphi delphi-xe2

所以,我想按长度排序字符串数组(更长的字符串先排序),如果长度相同,则按字母顺序排序。到目前为止,这是:

uses
  System.Generics.Defaults
  , System.Types
  , System.Generics.Collections
  ;

procedure TForm2.FormCreate(Sender: TObject);
var
  _SortMe: TStringDynArray;
begin
  _SortMe := TStringDynArray.Create('abc', 'zwq', 'Long', 'longer');

  TArray.Sort<string>(_SortMe, TDelegatedComparer<string>.Construct(
    function(const Left, Right: string): Integer
    begin
      Result := CompareText(Left, Right);
    end));
end;

预期结果:更长,更长,abc,zwq

2 个答案:

答案 0 :(得分:4)

调整匿名功能:

function(const Left, Right: string): Integer
    begin
      //Compare by Length, reversed as longest shall come first
      Result := CompareValue(Right.Length, Left.Length);
      if Result = EqualsValue then
        Result := CompareText(Left, Right);
    end));

您需要将System.Math和System.SysUtils添加到您的用途中。

答案 1 :(得分:1)

我本来会使用TStringList ......

任何方式,只需自定义比较功能:

  TArray.Sort<string>(_SortMe, TDelegatedComparer<string>.Construct(
    function(const Left, Right: string): Integer
    begin
      Result := length(Right) - length(Left); // compare by decreasing length
      if Result = 0 then
        Result := CompareText(Left, Right);  // compare alphabetically
    end));