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

How to sort string array by length?

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

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

正在调整您的匿名函数:

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 添加到您的用途中。

我会为此使用 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));