How to sort a string with digits and letters (digits before letters) in Rust

1 Answer

0 votes
use std::cmp::Ordering;
 
fn custom_sort(input: &str) -> String {
    let mut chars: Vec<char> = input.chars().collect();
 
    chars.sort_by(|&a, &b| {
        if a.is_digit(10) && b.is_alphabetic() {
            return Ordering::Less; // Digits before letters
        }
        if a.is_alphabetic() && b.is_digit(10) {
            return Ordering::Greater; // Letters after digits
        }

        a.cmp(&b)
    });
 
    chars.iter().collect()
}
 
fn main() {
    let input = "d2a54be3c1";
    let sorted_input = custom_sort(input);
 
    println!("Custom sorted string: {}", sorted_input);
}
 
   
    
/*
run:
    
Custom sorted string: 12345abcde
    
*/

 



answered May 27 by avibootz
...