To find the longest word in a given string in Rust, we can split the string into individual words and then find the longest word among them. Here is one way to do it:
main.rs405 chars17 lines
Here, we define a function find_longest_word
, which takes a string slice s
as input and returns a string slice as output. First, we split the input string into individual words using the split
method, which splits the string at the given delimiter (in this case, a space character). Next, we create a variable longest_word
and initialize it to the empty string ""
. We will use this variable to keep track of the longest word we have seen so far.
Next, we iterate over each word in the words
iterator using a for
loop. For each word, we check if its length is greater than the length of longest_word
. If it is, we update longest_word
to be the current word.
Finally, we return longest_word
from the function.
In the main
function, we test find_longest_word
with a sample string and print the result to the console. The output of this program would be:
main.rs20 chars2 lines
which is correct, since "jumps" is the longest word in the input string.
gistlibby LogSnag