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;