find the kth longest word in a string in rust

To find the kth longest word in a string in Rust, you can split the string using whitespace and then sort the resulting vector of words by descending length. Finally, you can return the kth element of the sorted vector.

Here's an example implementation:

main.rs
fn kth_longest_word(s: &str, k: usize) -> Option<&str> {
    // split the string into words
    let mut words: Vec<&str> = s.split_whitespace().collect();
    // sort the words by descending length
    words.sort_by_key(|w| w.len());
    words.reverse();
    // return the kth longest word
    words.get(k - 1).cloned()
}

fn main() {
    let s = "The quick brown fox jumps over the lazy dog";
    assert_eq!(kth_longest_word(s, 1), Some("lazy"));
}
450 chars
15 lines

In this example, the kth_longest_word function takes a string s and a number k and returns an Option<&str> representing the kth longest word in the string. If the string contains fewer than k words, the function returns None.

To split the string into words, we use the split_whitespace method of the str type to create a vector of &str elements. We then sort the vector by key, where the key is the length of each word, in ascending order. Finally, we reverse the vector so that the longest words are at the beginning of the vector.

To return the kth longest word, we use the get method of the Vec type to retrieve the element at the index k - 1. We use k - 1 because vector indices are zero-based, whereas k is one-based. The cloned method is used to create a copy of the string slice that lives as long as the vector.

In the main function, we test the implementation using a sample string and the assert_eq macro to compare the result of kth_longest_word with the expected result.

gistlibby LogSnag