IRsoft - Software and more by Ingmar Runge

Delphi strnatcmp + natsort

I needed a natural sort function for Delphi. As I found only a not really working solution on the web, I decided to take the original C code for Natural Order String Comparison by Martin Pool and to create a Delphi wrapper for it. This makes it possible to use the same alghoritm that PHP uses in its strnatcmp, strnatcasecmp and natsort functions in your projects.

Yeah, well, the rest is relatively unspectacular. Just add strnatcmp to your uses clause and call one of the exported functions:

function NatCompareText(const S1, S2: String): Integer;
function NatCompareStr(const S1, S2: String): Integer;
Parsed in 0.014 seconds, using GeSHi © 2005 Nigel McNie

The return values match those of standard text comparision functions like strcmp.

And here's an example how to sort a TStringList naturally:

uses strnatcmp;

// ...

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

// ...

var
  FileNames: TStringList;

// ...

FileNames.CustomSort(Compare_NaturalSort); // apply natural sorting

// ...
 
Parsed in 0.034 seconds, using GeSHi © 2005 Nigel McNie

Download: The zip file includes the C object file, the strnatcmp.pas and the file CHelpers.pas. The latter has been taken from Jan Goyvaerts' Delphi wrapper around PCRE. The patched version of the original strnatcmp source code is also included.

Last edited by Ingmar on Friday, May 26th 2006 15:48:29 CEST