split_whitespace reads words separated by any amount of whitespace without keeping the separators.

Program

Play the program to choose raw text and collect its visible words.

raw
split_whitespace_words.rs
Replay: real traced execution (multi-file project)
fn main() {
    let raw = "alpha beta";
    let words: Vec<&str> = raw.split_whitespace().collect();
    println!("{:?}", words);
}
fn main() {
    let raw = " alpha  gamma ";
    let words: Vec<&str> = raw.split_whitespace().collect();
    println!("{:?}", words);
}
fn main() {
    let raw = "";
    let words: Vec<&str> = raw.split_whitespace().collect();
    println!("{:?}", words);
}
  1. raw ← "alpha beta", words ← ["alpha", "beta"]

    1fn main() {2    let ra→ "alpha beta"w = "alpha beta"; //@raw="alpha beta", " alpha  gamma ", ""3    let word→ ["alpha", "beta"]s: Vec<&str> = raw.split_whitespace().collect();4    println!("{:?}", words);5}
    output["alpha", "beta"]
  1. raw ← " alpha gamma ", words ← ["alpha", "gamma"]

    1fn main() {2    let ra→ " alpha  gamma "w = " alpha  gamma ";3    let word→ ["alpha", "gamma"]s: Vec<&str> = raw.split_whitespace().collect();4    println!("{:?}", words);5}
    output["alpha", "gamma"]
  1. raw ← "", words ← []

    1fn main() {2    let ra→ ""w = "";3    let word→ []s: Vec<&str> = raw.split_whitespace().collect();4    println!("{:?}", words);5}
    output[]

Follow the Words

  1. raw starts as alpha beta.
  2. split_whitespace() treats the space as a separator.
  3. It yields alpha, then beta.
  4. collect() stores the words in a vector.
  5. The program prints ["alpha", "beta"]. | raw text | collected words | | --- | --- | | alpha beta | ["alpha", "beta"] | | alpha gamma | ["alpha", "gamma"] | | empty string | [] | @exercise split_whitespace_words.rs "Reproduce ["alpha", "beta"], then use the pinned raw variants with extra spaces and the empty string to predict ["alpha", "gamma"] and []."
split_whitespace `split_whitespace` treats spaces, tabs, and newlines as separators.
borrowing The collected `&str` values borrow slices from the original string.
empty input An empty or all-whitespace string produces an empty iterator.