在Delphi中自定义排序方法来排序字符串列表 [英] custom sort method in Delphi to sort list of strings

查看:1650
本文介绍了在Delphi中自定义排序方法来排序字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试排序一个文件列表(它们存储为字符串列表)在Delphi中,其名称如下所示

  a_1.xml 
a_20.xml
a_10.xml
a_2.XML

当我使用快速排序排序文件名时,它会按如下方式排列文件名称

  a_1.xml 
a_10.xml
a_2.xml
a_20.XML

但是,我希望以下列方式对文件名进行排序:

  a_1.xml 
a_2.xml
a_10.xml
a_20.XML

任何帮助将不胜感激。

解决方案

您可以使用Explorer使用的相同的比较功能,即 StrCmpLogicalW

  function StrCmpLogicalW(psz1,psz2:PWideChar):Integer;标准
external'shlwapi.dll';

函数StrCmpLogical(const s1,s2:string):整数;
begin
结果:= StrCmpLogicalW(PChar(s1),PChar(s2));
结束

如果您的字符串在 TStringList 那么您可以使用其 CustomSort 方法。这个预期是这种形式的比较函数:

  TStringListSortCompare = function(List:TStringList; 
Index1,Index2:Integer ): 整数;

所以,feed CustomSort 这个功能: / p>

  function StringListCompareLogical(List:TStringList; 
Index1,Index2:Integer):Integer;
begin
结果:= StrCmpLogical(List [Index1],List [Index2]);
结束


I am trying to sort a list of files (they are stored as list of strings) in Delphi whose names look like below

a_1.xml
a_20.xml
a_10.xml
a_2.XML

when i use quick sort to sort the file names, it sorts the file names as below

a_1.xml
a_10.xml
a_2.xml
a_20.XML

But, I want the file names to be sorted in the below fashion

a_1.xml
a_2.xml
a_10.xml
a_20.XML

Any help will be greatly appreciated.

解决方案

You can use the same compare function that Explorer uses, namely StrCmpLogicalW.

function StrCmpLogicalW(psz1, psz2: PWideChar): Integer; stdcall;
  external 'shlwapi.dll';

function StrCmpLogical(const s1, s2: string): Integer;
begin
  Result := StrCmpLogicalW(PChar(s1), PChar(s2));
end;

If you have your strings in a TStringList instance then you can use its CustomSort method. This expects a compare function of this form:

TStringListSortCompare = function(List: TStringList; 
  Index1, Index2: Integer): Integer;

So, feed CustomSort this function:

function StringListCompareLogical(List: TStringList; 
  Index1, Index2: Integer): Integer;
begin
  Result := StrCmpLogical(List[Index1], List[Index2]);
end;

这篇关于在Delphi中自定义排序方法来排序字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆