How to reverse only the alphabetic characters in a string, keeping other characters in place with Rust

1 Answer

0 votes
fn reverse_only_alphabetic_characters(s: &str) -> String {
    let mut chars: Vec<char> = s.chars().collect();
    let mut i = 0usize;
    let mut j = chars.len().saturating_sub(1);

    while i < j {
        if !chars[i].is_alphabetic() {
            i += 1;
        } else if !chars[j].is_alphabetic() {
            j -= 1;
        } else {
            chars.swap(i, j);
            i += 1;
            j -= 1;
        }
    }

    chars.into_iter().collect()
}

fn main() {
    let s = "a1-bC2-dEf3-ghIj";

    println!("{}", s);
    println!("{}", reverse_only_alphabetic_characters(s));
}




/*
run:

a1-bC2-dEf3-ghIj
j1-Ih2-gfE3-dCba

*/

 



answered Mar 6 by avibootz

Related questions

...