How to sort a string in the order: lowercase letters - uppercase letters - odd digits - even digits in C++

1 Answer

0 votes
#include <iostream>
#include <algorithm>
#include <string>

/*
    We want to sort characters in this strict order:
    1. lowercase letters   (a–z)
    2. uppercase letters   (A–Z)
    3. odd digits          (1,3,5,7,9)
    4. even digits         (0,2,4,6,8)

    To do this efficiently, we assign each character a "category rank"
    and then sort by:
        (category rank, natural character order)
*/

/// Returns category rank for sorting.
/// Lower rank = comes earlier.
int category(char c) {
    if (c >= 'a' && c <= 'z') return 0;   // lowercase
    if (c >= 'A' && c <= 'Z') return 1;   // uppercase
    if (c >= '0' && c <= '9') {
        int d = c - '0';
        return (d % 2 == 1) ? 2 : 3;      // odd digits → 2, even digits → 3
    }
    return 4; // fallback (should not happen for alphanumeric input)
}

/// Custom comparator for std::sort
bool customCompare(char a, char b) {
    int ca = category(a);
    int cb = category(b);

    if (ca != cb)
        return ca < cb;   // sort by category first

    return a < b;         // tie-breaker: natural order
}

int main() {
    std::string s = "a2B3cD8f1Z0";

    // Sort using our custom comparator
    std::sort(s.begin(), s.end(), customCompare);

    std::cout << "Sorted result: " << s << "\n";
}


/*
run:

Sorted result: acfBDZ13028

*/

 



answered Jul 13 by avibootz

Related questions

...