c# - 在自定义程序中使用原生 Windows 自然顺序排序
问题描述
作为程序员,您可能不得不使用或创建某种字符串比较函数。通常,这些非常简单:
function compare(s1, s1) { return s1.toLowerCase() - s2.toLowerCase(); }
这适用于绝大多数情况。但是,Windows (XP 和更高版本)对文件的排序方式不同——而且更好!- 比一个糟糕的 ASCII 实现。
如何在自定义程序中创建原生 Windows 自然顺序排序的最小、完整和可验证示例?
我读过的所有内容都指向StrCmpLogicalW
在shlwapi.dll
. 那太棒了!但是如何在自定义 C/C++ 程序中使用这个函数呢?
我对重新实现比较功能不感兴趣。我已经看到了这个,这个,这个,这个,还有这个。这些无疑是非常接近的近似值,但我只想在我的程序中链接或调用 Windows API 函数。
以下是我已经研究和尝试过的其他一些事情:
- 阅读 Microsoft 的文档
shlwapi.dll
和StrCmpLogicalW
从 Microsoft获取的文档 - 在 StackOverflow 上找到从早期问答中发布的(据说)完整程序
- 为 C++ 和 C# 版本的 Visual Studio 2010 Express 编译几个小代码示例(
fatal error C1190: managed targeted code requires a '/clr' option
...真的吗?) - 为 Visual Studio 2012 Express 编译几个小代码示例,因为一些文章说这将摆脱早期关于
/clr
选项的编译错误,但只是得到了一堆不同的编译错误 - 尝试使用 MinGW 为 Eclipse C++ 编译几个小代码示例
当我第一次开始研究这个时,我想,“这只是 Windows API,这很容易!” 我还没有提出任何语言的工作程序。
我从事 C/C++ 和 Unix/DOS/Windows shell 脚本编写已有很长时间了,使用 API 从未如此令人厌烦。微软,你真丢脸。
另外,我已经阅读了有关 ASCII 排序的咆哮,但谢谢。这些包含了一些良好思维的肥沃土壤。
https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/
http://weblog.masukomi.org/2007/12/10/alphabetical-asciibetical/
解决方案
C++:
#include <windows.h>
#include <shlwapi.h>
#pragma comment(lib, "shlwapi.lib")
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
bool str_cmp_logical(std::wstring const &lhs, std::wstring const &rhs)
{
return StrCmpLogicalW(lhs.c_str(), rhs.c_str()) < 1;
}
int main()
{
std::vector<std::wstring> foo{
L"20string", L"2string", L"3string", L"st20ring", L"st2ring",
L"st3ring", L"string2", L"string20", L"string3"
};
for (auto const &f : foo)
std::wcout << f << L' ';
std::wcout.put(L'\n');
std::sort(foo.begin(), foo.end(), str_cmp_logical);
for (auto const &f : foo)
std::wcout << f << L' ';
std::wcout.put(L'\n');
}
输出:
20string 2string 3string st20ring st2ring st3ring string2 string20 string3
2string 3string 20string st2ring st3ring st20ring string2 string3 string20
尝试使用 MinGW 编译代码失败,因为<shlwapi.h>
它的包附带的版本w32api
没有为StrCmpLogicalW()
. 当我自己宣布时,我得到了
C:\MinGW\bin>"g++.exe" -lshlwapi C:\Users\sword\source\repos\Codefun\main.cpp
C:\Users\sword\AppData\Local\Temp\ccMrmLbD.o:main.cpp:(.text+0x23): undefined reference to `StrCmpLogicalW(wchar_t const*, wchar_t const*)'
collect2.exe: error: ld returned 1 exit status
所以 MinGW 附带的库似乎不知道StrCmpLogicalW()
.
不过,它应该适用于 Mingw-w64。
推荐阅读
- java - How to read txt file from Google Drive?
- ffmpeg - ffmpeg 管道图像到 redis
- php - PHP,循环内添加的新键和值在循环外消失
- linux - 在谷歌云上运行 nohup 后 Chromedriver 关闭
- python - 列表的 Python Vlookup 函数
- python - 如何覆盖以前的打印文本?
- rcpp - 从 NumericVector 创建 NumericMatrix
- python - 最小化涉及大型加权矩阵的平方和的最快方法
- android - Flutter:适用于 Windows / Linux 的 iOS 模拟器来运行 Flutter 应用程序?
- azure - (Microsoft Academic Knowledge Exploration Service)DeployHost 过程中需要帮助