How to Split a String in Rust

Split a string in Rust using split_whitespace() for spaces or split() with a custom delimiter to iterate over substrings.

Use the split_whitespace() method to split a string by any whitespace or split() with a specific delimiter to get an iterator of substrings.

let text = "hello world wonderful world";
for word in text.split_whitespace() {
    println!("Word: {}", word);
}

For a specific delimiter like a period:

let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence = novel.split('.').next().unwrap();
println!("First sentence: {}", first_sentence);