OneBite.Dev - Coding blog in a bite size

Split A String By Empty Space In Rust

Code snippet for how to Split A String By Empty Space In Rust with sample and detail explanation

When programming in Rust, a scenario may occur where you need to split a string by empty space. This article will guide you exactly on how to do so.

Code snippet: Split a String by Empty Space in Rust

To split a string by space in Rust, you can use the split_whitespace() method like this:

fn main() {
    let msg = "Hello World from Rust!";
    let words: Vec<&str> = msg.split_whitespace().collect();

    println!("{:?}", words);
}

In this code snippet, “Hello World from Rust!” is the string being used. The split_whitespace() method splits this message into separate words at each whitespace, and these words are collected into a Vector.

Code Explanation: Split a String by Empty Space in Rust

Let’s break down the code and understand it step by step.

  1. fn main(): This function is where the execution of the program starts.

  2. let msg = "Hello World from Rust!";: Here, we declare a string with the value “Hello World from Rust!” which is assigned to the variable msg.

  3. let words: Vec<&str> = msg.split_whitespace().collect();: In this step, we use the split_whitespace() method for the msg string, which splits the string at each whitespace. The collect() method is then used to collect the split words into a Vector of strings. This vector is stored in the words variable.

  4. println!("{:?}", words);: Lastly, the words vector that contains the separated words is printed out using the println! macro. The {:?} placeholder syntax is used to print out the debug formatting of words.

Note that the split_whitespace() function is a more flexible version of the split() function. It splits the string not just at space characters, but at all kinds of whitespace characters. This includes tabs (\t), line breaks (\n), and so on.

rust