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 win7,win2008,win2003,winxp 屏蔽ctrl+alt+del

如何在Delphi xe中通过ftp下载文件

Delphi删除文件和文件夹

Delphi 将自己的app.ico应用程序图表添加到dephi资源文件res中

Delphi中如何实现模糊查找文件

Delphi 脉搏波9808血压计读取测试程序

Delphi 在firemonkey应用程序中使用torientationsensor获取设备倾斜和指南针航向

Delphi android ios 获取packagename

Delphi 添加或解除引号

Delphi中的free和nil

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



打赏

取消

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

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

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

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

评论

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