how to split a string by spaces rust
To split a string by spaces in Rust, you can use the split_whitespace()
method from the SplitWhitespace
iterator. Here's an example:
fn main() {
let my_string = "Hello Rust programming";
let split_result: Vec<&str> = my_string.split_whitespace().collect();
println!("{:?}", split_result);
}
This code splits the my_string
variable into substrings based on whitespace and collects them into a Vec<&str>
. The resulting vector, split_result
, will contain the individual words from the original string. Finally, the code prints the contents of the split_result
vector.
This will produce the following output:
["Hello", "Rust", "programming"]
In this example, the split_whitespace()
method splits the string at every whitespace character (spaces, tabs, and newlines), resulting in the individual words being stored as separate elements in the vector.