本文整理自网络,侵删。
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 getdrivetypea() 查看驱动器类型
更多相关阅读请进入《Delphi》频道 >>