总结:
- For Windows (version >= XP), Windows Explorer utilizes natural sort.
- For Linux terminals: use "ls -v" instead of plain "ls" to get natural sort.
字母排序算法的http://irsoft.de/web/strnatcmp-and-natsort-for-delphi
http://www.davekoelle.com/alphanum.html
http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html
http://objectmix.com/delphi/722211-natural-sorting-optimizing-working-solution.html
http://objectmix.com/delphi/401713-alphanumeric-sort-routine-delphi.html
==========================
以下文件名将在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终端或CentOS等Linux发行版的xterm终端中进行排序,如下所示:
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资源管理器中相同的顺序?欢迎提出任何建议!
附言:我的Windows区域设置为中文,但我认为英语区域设置也是如此。
发布于 2011-02-28 01:48:49
StrCmpLogicalW能够处理数字,另一种选择是CompareString
发布于 2011-02-28 02:15:34
感谢Anders -答案是StrCmpLogicalW;我在Delphi2009源代码中没有找到它的声明,所以我在下面的测试中自己声明了它:
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;
https://stackoverflow.com/questions/5134712
复制相似问题