How to split a string

Use split_whitespace() to separate words by spaces or split() with a delimiter to break a string at specific characters in Rust.

Use the split_whitespace() method to break a string into words or split() with a delimiter to break it at specific characters.

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

To split by a specific character like a period, use split('.') and handle the resulting iterator:

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