Reverses all of the words within the string

so that it reverses all of the words within the string passed in.

Example(Input --> Output):

"The greatest victory is that which requires no battle" --> "battle no requires which that is victory greatest The"
```y
fn reverse(s: &str) -> String {
    s.split(' ').rev().collect::<Vec<_>>().join(" ")
}

// or this with nightly feature
fn reverse2(s: &str) -> String {
    s.split(' ').rev().intersperse(" ").collect()
}

playground

Edit: You can define reverse2 in stable Rust with itertools crate

fn reverse2(s: &str) -> String {
    itertools::Itertools::intersperse(s.split(' ').rev(), " ").collect()
}
2 Likes

Your problem statement is underspecified. For example:

"¿What\nshould the\nresult of processing\n* this *\nstring be?"

Note that the fully-general version of this problem is quite tricky, and many text-handling programs have trouble with it.

4 Likes