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