直接上代码:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cctype>
// Function to compare two strings in a natural way
bool naturalCompare(const std::string& a, const std::string& b) {
size_t i = 0, j = 0;
while (i < a.size() && j < b.size()) {
// Skip leading zeros in numbers
if (std::isdigit(a[i]) && std::isdigit(b[j])){
size_t valA = 0, valB = 0;
std::string strA {};
std::string strB {};
while(i < a.length() && std::isdigit(a[i])) {
valA += (a[i] -'0');
if(valA != 0) {
strA.push_back(a[i]);
}
i++;
}
while(j < b.length() && std::isdigit(b[j])) {
valB += (b[j] -'0');
if(valB != 0) {
strB.push_back(b[j]);
}
j++;
}
if(strA != strB && strA.size() == strB.size()) {
return strA <strB;
}
if(strA != strB && strA.size() != strB.size()) {
return strA.size() <strB.size();
}
} else {
// Compare characters if not both are digits
if (a[i] != b[j]) {
return a[i] < b[j];
}
++i;
++j;
}
}
// If we reach the end of one of the strings
return a.size() < b.size();
}
int main() {
std::vector<std::string> vec = {"b3", "", "file1.txt", "file20.txt",
"fi.txt","a","15","C10",
"c00013A","c0013A","c00000013A","00000013A",
""," ","&&&__","$%^&*()()++",
"99999999999999999999999999999999999999999","9999999999999999999999aaa9999999999999999999","9999999999999999999999AAA9999999999999999999",
"a_123456789123456789abc","a_123456789123456789bbc",
"bcm123bbc445","bcm123bbc4","bcm123bbc4451","bcm123bbc445kk"};
// Sort the vector using the naturalCompare function
std::sort(vec.begin(), vec.end(), naturalCompare);
// Print the sorted vector
for (const auto& str : vec) {
std::cout << str << std::endl;
}
return 0;
}
代码说明:
.数字和字符分开
判断是否是数字
将a的数字提取到strA,(不加入前缀0,但是中间的0需要)
将b的数字提取到strB
比较strA和strB是否相等 && strA和strB的size是否相等(不相等,而且位数也不相等)
按照位数(size)排序
比较strA和strB是否相等 && strA和strB的size是否相等(不相等,而且位数相等)
按照字母顺序表排序
是字符:
按照字母顺序表进行排序。