How to reverse each word in a string with Rust

1 Answer

0 votes
fn reverse_each_word_in_string(s: &str) -> String {
    let words: Vec<&str> = s.split(" ").collect();
    
    let reversed_words: Vec<String> = words.iter()
        .map(|&word| word.chars().rev().collect())
        .collect();
    
    reversed_words.join(" ")
}

fn main() {
    let s = "java c++ rust python c#";
    
    println!("{}", reverse_each_word_in_string(s));
}



  
/*
run:

avaj ++c tsur nohtyp #c

*/

 



answered Aug 31, 2024 by avibootz
...