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

1 Answer

0 votes
/*
    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)

    Strategy:
    ---------
    Assign each character a "category rank" and sort by:
        (category rank, natural character order)

    Swift’s built‑in sorted(by:) with a custom comparator
    is the idiomatic and efficient way to do this.
*/

import Foundation

/// Returns category rank for sorting.
/// Lower rank = comes earlier.
func category(_ c: Character) -> Int {
    if c.isLowercase { return 0 }                 // lowercase
    if c.isUppercase { return 1 }                 // uppercase

    if c.isNumber {
        let d = Int(String(c))!
        return d % 2 == 1 ? 2 : 3                 // odd → 2, even → 3
    }

    return 4                                      // fallback (should not happen)
}

/// Custom comparator for sorting characters
func compareChars(_ a: Character, _ b: Character) -> Bool {
    let ca = category(a)
    let cb = category(b)

    if ca != cb {
        return ca < cb                            // sort by category first
    }

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

func sortAlphaNumeric(_ s: String) -> String {
    let arr = Array(s)
    let sorted = arr.sorted(by: compareChars)
    return String(sorted)
}

let s = "a2B3cD8f1Z0"
let result = sortAlphaNumeric(s)

print("Sorted result:", result)



/*
run:

Sorted result: acfBDZ13028

*/

 



answered 12 hours ago by avibootz

Related questions

...