How to reverse the order of the words in a string with Rust

1 Answer

0 votes
fn main() {
    let s = "aaa bbb ccc ddd eee";
    
    let reversed_string_words = reverse_words(&s);
    
    println!("{}", reversed_string_words);
}

fn reverse_words(s: &str) -> String {
    let words: Vec<&str> = s.split_whitespace().collect();
    let reversed: Vec<&str> = words.iter().rev().map(|&word| word).collect();
    
    reversed.join(" ")
}

 
    
/*
run:
 
eee ddd ccc bbb aaa
   
*/

 



answered Feb 6, 2025 by avibootz
edited Feb 6, 2025 by avibootz
...