TypingKit
← Code

Rust: Find the longest word

Written for TypingKit · ~2 min

0 wpm 100% accuracy 100% real accuracy
fn longest_word(text: &str) -> Option<&str> {↵
text.split_whitespace()↵
.map(|w| w.trim_matches(|c: char| !c.is_alphanumeric()))↵
.filter(|w| !w.is_empty())↵
.max_by_key(|w| w.len())↵
}↵
↵
fn main() {↵
let line = "It was the best of times, it was the worst of times.";↵
match longest_word(line) {↵
Some(word) => println!("longest: {word}"),↵
None => println!("no words"),↵
}↵
}