How to Split a String by Space in Rust

We can split a String in Rust based on spaces by making use of the split_whitespace() method.

The split_whitespace() method returns an iterator which can be collect as Vec<&str> using the collect() method.

Example:
fn main() {
    
    let data_string = "This is my String that I want to Split";
    let splitted_str: Vec<&str> = data_string.split_whitespace().collect();

    for word in splitted_str {
        println!("{}", word);
    }
}
Output:
This
is
my
String
that
I
want
to
Split
How to Split a String in Rust

Documentation:
  1. https://doc.rust-lang.org/
  2. https://doc.rust-lang.org/std/primitive.str.html#method.split_whitespace
  3. https://doc.rust-lang.org/std/vec/struct.Vec.html#methods
  4. https://doc.rust-lang.org/std/iter/trait.Iterator.html

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!