find the shortest word in a string in rust

To find the shortest word in a string in Rust, you can split the string into words using the split method, which returns an iterator. Then, you can use the min_by method of the iterator to find the shortest word based on its length.

Here's an example code snippet that demonstrates this:

main.rs
fn find_shortest_word(s: &str) -> Option<&str> {
    s.split_whitespace().min_by(|a, b| a.len().cmp(&b.len()))
}

fn main() {
    let s = "Hello world! Rust is awesome.";
    let shortest = find_shortest_word(s).unwrap();
    println!("Shortest word: {}", shortest);
}
269 chars
10 lines

In this example, the find_shortest_word function takes a string slice s as input and returns an Option<&str>, which will be Some if there is at least one word in the string, or None if the string is empty.

Inside the function, the split_whitespace method is used to split the string into words. This method returns an iterator over the words, which we can then chain with the min_by method to find the shortest word based on its length. The min_by method takes a closure that compares the lengths of two words and returns an ordering, which is used to determine the minimum value.

Finally, in the main function, we call find_shortest_word with a test string, and use unwrap to get the shortest word from the Option value. We then print the shortest word to the console.

gistlibby LogSnag