How to move all special characters to the beginning of a string in Rust

1 Answer

0 votes
fn move_special_characters_to_beginning(s: &str) -> String {
    let mut specials = String::new();
    let mut chars = String::new();

    for ch in s.chars() {
        if ch.is_alphanumeric() || ch.is_whitespace() {
            chars.push(ch);
        } else {
            specials.push(ch);
        }
    }

    specials + &chars
}

fn main() {
    let s = "c++23$c&^java*(rust) php <>/python 3.14.2";
    
    let result = move_special_characters_to_beginning(s);
    
    println!("{}", result);
}



/*
run:

++$&^*()<>/..c23cjavarust php python 3142

*/

 



answered Dec 12, 2025 by avibootz

Related questions

...