如果字母类型相同,则先将小写字母排序

问题描述 投票:0回答:1

如果字母类型相同,如何将

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
c++ locale
1个回答
0
投票

就像这样假设你想要输出

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.