rust split string into words
To split a string into words in Rust, you can utilize the split_whitespace
method provided by the str
type. Here's an example:
fn main() {
let sentence = "Hello, world! This is a sentence.";
let words: Vec<&str> = sentence.split_whitespace().collect();
println!("{:?}", words);
}
The split_whitespace
method splits the string into words based on whitespace characters (spaces, tabs, newlines, etc.). It returns an iterator over the words, which we can collect into a Vec<&str>
to store each word separately. In the example above, the output will be ["Hello,", "world!", "This", "is", "a", "sentence."]
.
You can modify this example to suit your specific needs.