find the longest word in a string in rust

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.rs
fn find_longest_word(s: &str) -> &str {
    let words = s.split(' ');
    let mut longest_word = "";
    for word in words {
        if word.len() > longest_word.len() {
            longest_word = word;
        }
    }
    longest_word
}

fn main() {
    let s = "The quick brown fox jumps over the lazy dog";
    let longest_word = find_longest_word(s);
    println!("Longest word: {}", longest_word);
}
405 chars
17 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.rs
Longest word: jumps
20 chars
2 lines

which is correct, since "jumps" is the longest word in the input string.

gistlibby LogSnag