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.
-
fn main()
: This function is where the execution of the program starts. -
let msg = "Hello World from Rust!";
: Here, we declare a string with the value “Hello World from Rust!” which is assigned to the variablemsg
. -
let words: Vec<&str> = msg.split_whitespace().collect();
: In this step, we use thesplit_whitespace()
method for themsg
string, which splits the string at each whitespace. Thecollect()
method is then used to collect the split words into a Vector of strings. This vector is stored in thewords
variable. -
println!("{:?}", words);
: Lastly, thewords
vector that contains the separated words is printed out using theprintln!
macro. The{:?}
placeholder syntax is used to print out the debug formatting ofwords
.
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.