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

标签 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;

预期结果:long、Long、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 添加到您的用途中。

关于arrays - 如何按长度对字符串数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48032695/

相关文章:

javascript - 合并数组只添加新元素

delphi - 使用 Delphi 在 Excel 工作表的每一行插入图像

windows - 在 Delphi 窗体上递归更新字体

c - C中通过指针修改函数中数组的值

javascript - 如何检查函数是否已执行?

c# - 根据条件从列表创建属性值数组

c++ - 结构未完成排序

mongodb - 排序优先级

python - 根据列(字符串)对 pandas 中的 CSV 进行排序

delphi - 在 Delphi 中实现 OAuth 提供程序