在文件夹中,我们经常有类似s_1.txt、s_2.txt、s_10.txt、s_11.txt这样的命名方式,我们期望的排序方式是s_1.txt、s_2.txt、s_10.txt、s_11.txt(XP & Vista & Windows7是这种方式),然而,按照常规的字符串排序算法的到的结果是s_1.txt、s_10.txt、s_11.txt、s_2.txt(Windows 2000是这种方式)。
新的排序算法的规则是:
-
非数字部分按照字符串排序
-
数字部分按照大小排序
-
规则1的优先级高于规则2的优先级
在网上看到有人讨论怎么实现上面的智能排序效果,甚至自己写了一些算法,其实Windows就有API函数来实现文件名的智能排序规则。
StrCmpLogicalW
/*
Compares two Unicode strings. Digits in the strings are considered as numerical content rather than text. This test is not case sensitive.
Syntax
int StrCmpLogicalW( LPCWSTR psz1, LPCWSTR psz2 );
Parameters
- psz1
- [in] A pointer to the first null-terminated string to be compared.
- psz2
- [in] A pointer to the second null-terminated string to be compared.
Return Value
- Returns zero if the strings are identical.
- Returns 1 if the string pointed to by psz1 has a greater value than that pointed to bypsz2.
- Returns -1 if the string pointed to by psz1 has a lesser value than that pointed to bypsz2.
*/
C# 示例代码:
public class StringLogicalComparer: IComparer
{
[DllImport("shlwapi.dll", CharSet=CharSet.Unicode, ExactSpelling=true)]
public static extern int StrCmpLogicalW(string x, string y);public int Compare(object x, object y)
{
return StrCmpLogicalW((string)x, (string)y);
}
}
使用委托示例:
FileInfo[] sfiles = sourceInfo.GetFiles(“*.txt”, SearchOption.AllDirectories);
Array.Sort<FileInfo>(sfiles, delegate(FileInfo a, FileInfo b)
{
return StrCmpLogicalW(a.Name, b.Name);
});
原创文章,转载请注明: 转载自闲云博客
本文链接地址: 文件名智能排序的规则与算法
留下评论







1 Comment(s)