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 to do this .

  • Using the split Function

    The split function within the String object separates the string based on a specified pattern and returns an iterator.

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

    You can iterate over the result using a for loop, or you can convert it to a 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 function

    The split_whitespace function returns an iterator by splitting the string using whitespace as the 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]);
    }