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 readprocessmemory用法

字符串截取小例子Delphi源代码

Delphi 无法打不开读取文件名有逗号的文件

Delphi base64编码/解码及zlib压缩/解压

Delphi 通过api 隐藏任务栏所有托盘图标

Delphi 把单张图片保存到access数据库

Delphi webbrowser中模拟连接点击(非鼠标模拟)

Delphi里面判断一个字符串在另一个字符串中出现的次数

Delphi record,两种声明方式

Delphi中利用msdasc来配置数据库链接

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



打赏

取消

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

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

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

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

评论

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