C++ Builder xe 关于ListView的自然排序功能排序效果与Windows资源管理器相同
可以排序成:
99-150
100-150
101-150
核心算法在NaturalCompare
函数中:
int NaturalCompare(const String& str1, const String& str2) {
const wchar_t* p1 = str1.c_str();
const wchar_t* p2 = str2.c_str();
while (*p1 && *p2) {
// 跳过前导空格
while (*p1 == ' ') p1++;
while (*p2 == ' ') p2++;
// 检查数字部分
if (std::iswdigit(*p1) && std::iswdigit(*p2)) {
// 提取连续数字
String numStr1, numStr2;
while (*p1 && std::iswdigit(*p1)) numStr1 += *p1++;
while (*p2 && std::iswdigit(*p2)) numStr2 += *p2++;
// 转换为整数比较
long num1 = StrToInt64Def(numStr1, 0);
long num2 = StrToInt64Def(numStr2, 0);
if (num1 != num2)
return num1 < num2 ? -1 : 1;
}
// 检查字母部分(不区分大小写)
else if (std::iswalpha(*p1) && std::iswalpha(*p2)) {
wchar_t c1 = std::towlower(*p1++);
wchar_t c2 = std::towlower(*p2++);
if (c1 != c2)
return c1 < c2 ? -1 : 1;
}
// 特殊字符处理
else {
if (*p1 != *p2)
return *p1 < *p2 ? -1 : 1;
p1++;
p2++;
}
}
// 处理字符串长度不同的情况
if (!*p1 && *p2) return -1;
if (*p1 && !*p2) return 1;
return 0;
}