Reverse Words In A Sentence

Split a borrowed sentence into whitespace words, reverse the iterator, collect, and rejoin while the source string stays usable because nothing moved.

RustData Integrity

Code

rustsnippet
17 lines
fn main() {
    let sentence = "deploy notes for phase twenty";
    // reverse the word order: split borrowed, rev, collect, join
    let reversed = sentence
        .split_whitespace()
        .rev()
        .collect::<Vec<_>>()
        .join(" ");
    println!("{reversed}");

    // 只借不占:sentence 在上面之后依然可用
    let first = sentence.split_whitespace().next().unwrap_or("");
    println!("original first word: {first}");

    let words = sentence.split_whitespace().count();
    println!("word count: {words}");
}

Reverse Words In A Sentence: inside the code

Reverse Words In A Sentence reduces to the function main.

What to watch for

  • Prerequisite count: one — the toolchain itself.

Using it

The signature to know: fn main()

Output lines are prefixed (original first word:, word count:), so the line-to-step mapping stays readable.

Key statements

let first = sentence.split_whitespace().next().unwrap_or("");

Interactive Tools for This Topic

FAQ

What does Reverse Words In A Sentence print when run?
Running the file directly is enough — expect labeled output lines such as `original first word:`, `word count:`.