如何在Windows资源管理器中获取Delphi中的排序顺序?

SOU*_*ser 17 windows delphi sorting collation

综述:

  1. 我一直在寻找的术语似乎是"自然的排序".
  2. 对于操作系统中的行为:

    • 对于Windows(版本> = XP),Windows资源管理器使用自然排序.
    • 对于Linux终端:使用"ls -v"而不是普通的"ls"来获得自然排序.
  3. 对于Delphi中的编程,使用StrCmpLogicalW Windows API进行自然排序.

  4. 对于Delphi和Kylix&Lazarus中的编程,使用手工制作的函数进行自然排序:

==========================

将在Windows资源管理器中订购以下文件名,如下所示:

test_1_test.txt

test_2_test.txt

test_11_test.txt

test_12_test.txt

test_21_test.txt

test_22_test.txt

例如,如果我将它们放在TStringList实例中并调用Sort,则排序顺序如下:

test_1_test.txt

test_11_test.txt

test_12_test.txt

test_2_test.txt

test_21_test.txt

test_22_test.txt

为了记录,上述文件名将在Cygwin的rxvt终端或Linux发行版的xterm终端(如CentOS)中进行排序,如下所示:

test_11_test.txt

test_12_test.txt

test_1_test.txt

test_21_test.txt

test_22_test.txt

test_2_test.txt

您能否帮助评论如何理解排序行为的这种差异?此外,是否可以获得与Windows资源管理器中相同的顺序?任何建议表示赞赏!

PS:我的Windows语言环境设置为中文,但我认为英语语言环境也是如此.

And*_*ers 21

StrCmpLogicalW能够处理数字,另一种选择是CompareString


klu*_*udg 16

感谢Anders - 答案是StrCmpLogicalW; 我没有在Delphi 2009中找到它的声明,所以我在下面的测试中自己声明:

type
  TMyStringList = class(TStringList)
  protected
    function CompareStrings(const S1, S2: string): Integer; override;
  end;

function StrCmpLogicalW(P1, P2: PWideChar): Integer;  stdcall; external 'Shlwapi.dll';

function TMyStringList.CompareStrings(const S1, S2: string): Integer;
begin
  Result:= StrCmpLogicalW(PChar(S1), PChar(S2));
end;

procedure TForm11.Button2Click(Sender: TObject);
var
  SL: TMyStringList;

begin
  SL:= TMyStringList.Create;
  try
    SL.Add('test_1_test.txt');
    SL.Add('test_11_test.txt');
    SL.Add('test_12_test.txt');
    SL.Add('test_2_test.txt');
    SL.Add('test_21_test.txt');
    SL.Add('test_22_test.txt');
    SL.Sort;
    Memo1.Lines:= SL;
  finally
    SL.Free;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

  • @NGLN由于没有`StrCmpLogicalA`版本存在,你应该在调用`StrCmpLogicalW`之前将字符串转换为unicode,如果你有国家字符,可能使用`MultiByteToWideChar`函数 - http://msdn.microsoft.com/en-us/library/windows /desktop/dd319072(v=vs.85).aspx (2认同)