Delphi 按字符串长度对TStringList的元素进行排序


本文整理自网络,侵删。

 
Delphi的TStringList 除了具有以升序对列表中的字符串进行排序的Sort方法之外,还有一个CustomSort方法,该方法可以在任意条件下对字符串进行排序。介绍如何使用
TStringList的CustomSort方法按字符串长度排序。

CustomSort方法采用TStringListSortCompare类型的函数作为参数。
TStringListSortCompare类型定义如下:

TStringListSortCompare = function(List: TStringList; Index1, Index2: Integer): Integer;
创建一个比较TStringListSortCompare类型字符串的长度的函数。

function StringLengthCompare(List: TStringList; Index1, Index2: Integer): Integer;
begin
  Result := List[Index1].Length - List[Index2].Length;
end;
如果将此函数作为TStringList的CustomSort方法的参数传递,则将按字符串长度的顺序对其进行排序。

在以下示例应用程序中,当按下按钮时,将对TStringList中的字符串进行排序,并将结果显示在备注中。

将TButton和TMemo放在窗体上。
按下按钮后,将显示排序结果。

function StringLengthCompare(List: TStringList; Index1, Index2: Integer): Integer;
begin
  Result := List[Index1].Length - List[Index2].Length;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  stli: TStringList;
begin
  stli := TStringList.Create;

  // お?しデ?`タ格?{
  stli.Add('aa');
  stli.Add('a');
  stli.Add('aaaaa');
  stli.Add('aaaa');
  stli.Add('aaa');

  stli.CustomSort(StringLengthCompare);
  Memo1.Text := stli.Text;

  stli.Free;
end;

相关阅读 >>

Delphi sysutils.trim、sysutils.trimleft、sysutils.trimright - 删除空格

Delphi vclskin 5.40在2010安装方法

Delphi 通过api强制tedit仅接受数字输入

Delphi 能否把.txt文件的数据导入到access数据库中

Delphi 我的电脑连接到 internet 了吗?

Delphi判断系统是否安装tcp/ip协议

Delphi中使用ixmlhttprequest如何用post方式提交带参

Delphi 判断某个系统服务是否存在及相关状态

Delphi tstringlist自定义排序

Delphi 实现延时自动关闭对话框

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...

    正在狠努力加载,请稍候...