Start learning free

LESSON 67 OF 348 · STRINGS I

String Split in Rust in Rust

Lesson

In Rust, you can split a string into a vector of words by whitespace using the .split_whitespace() method and .collect():

// split_whitespace() splits a string into words by whitespace
let sentence = "hello world foo";
let words: Vec<&str> = sentence.split_whitespace().collect();
// words == ["hello", "world", "foo"]

Here is how the split works internally:

// split_whitespace() returns an iterator over substrings
// .collect() gathers the iterator into a Vec<&str>
let sentence = "hello world foo";
let words: Vec<&str> = sentence.split_whitespace().collect();

Assignment
Follow the Coding Tutorial and split sentence into a vector of words!


Hint
Use sentence.split_whitespace().collect() and assign the result to words.

STEP 1 OF 1
    Ctrl + Enter to check

    String Split in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free