How to split a Strings in Rust example

This tutorial shows you multiple ways to split a string with a separator.

How to Split a String with space in Rust?

There are multiple ways we can do it.

  • Use split function

split function in String object split the string using a pattern, returns an iterator.

The split method split a string into multiple slices using spaces, separators or characters

You can use for in loop to iterate the result, or you can convert it to Vec<&str> using the collect method.

fn main() {
    let name = "Hello John";

    for item in name.split(" ") {
        println!("{}", item);
    }
    let items: Vec<&str> = name.split(" ").collect();
    println!("{}", items[0]);
    println!("{}", items[1]);
}

Output:

Hello
John
Hello
John
  • split_whitespace function

split_whitespace function returns the iterator by splitting the string with the whitespace separator.

Here is an example program

fn main() {
    let name = "Hello John";

    for item in name.split_whitespace() {
        println!("{}", item);
    }
    let items: Vec<&str> = name.split_whitespace().collect();
    println!("{}", items[0]);
    println!("{}", items[1]);
}