如果字母类型相同,如何将
std::string
排序为小写在前?
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "aAbBcCdDeE";
std::sort(std::begin(str), std::end(str));
std::cout << str << std::endl;
}
电流输出:
ABCDEabcde
预期输出:
aAbBcCdDeE
就像这样假设你想要输出
abcdefABCDEF
#include <iostream>
#include <string>
#include <algorithm>
char inverted_case(const char c)
{
if (( c >= 'a') && (c <= 'z')) return std::toupper(c);
return std::tolower(c);
}
// an example function may not be correct for all alphabets
bool compare_lower_case_first(const char lhs, const char rhs)
{
return inverted_case(lhs) < inverted_case(rhs);
}
int main()
{
std::string str = "aAbBcCdDeE";
std::sort(std::begin(str), std::end(str), compare_lower_case_first);
std::cout << str << "\n";
return 0;
}