How to find the second largest word in a string with Rust

1 Answer

0 votes
fn find_second_largest_word(s: &str) -> Option<String> {
    let mut words: Vec<&str> = s.split_whitespace().collect();
    
    words.sort_by(|a, b| b.len().cmp(&a.len()));
    
    if words.len() < 2 {
        None
    } else {
        Some(words[1].to_string())
    }
}

fn main() {
    let sentence = "go c cpp cobol c# python java";
    
    match find_second_largest_word(&sentence) {
        Some(word) => println!("The second largest word is: {}", word),
        None => println!("There are not enough words in the string."),
    }
}

  
/*
run:
  
The second largest word is: cobol
 
*/

 



answered Jan 19, 2025 by avibootz
...