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.rs450 chars15 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