split a string into an array of words in rust

In Rust, to split a string into an array of words, we can use the split method of the string rust type. This method splits a string into substrings at any occurrence of a specified delimiter and returns an iterator over those substrings.

Here's an example:

main.rs
let my_string = String::from("Hello world, Rust is awesome!");
let words: Vec<&str> = my_string.split(" ").collect();

println!("{:?}", words);
144 chars
5 lines

This code will output:

main.rs
["Hello", "world,", "Rust", "is", "awesome!"]
46 chars
2 lines

We are using the split method with the delimiter of space character " ", and then collecting the substrings into a vector of &str. We can then work with this vector and perform any further processing required.

gistlibby LogSnag