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"
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()


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

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

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.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.