Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,945 questions

51,887 answers

573 users

How to find the largest and the smallest word in a string with Rust

1 Answer

0 votes
fn find_largest_and_smallest_words(text: &str) -> (Option<&str>, Option<&str>) {
    text.split_whitespace().fold((None, None), |(smallest, largest), word| {
        (
            smallest.map_or(Some(word), |s| if word.len() < s.len() { Some(word) } else { Some(s) }),
            largest.map_or(Some(word), |l| if word.len() > l.len() { Some(word) } else { Some(l) }),
        )
    })
}

fn main() {
    let s = "Rust is memory-efficient with no runtime or garbage collector";
    
    let (smallest, largest) = find_largest_and_smallest_words(s);
    
    println!("Smallest: {:?}", smallest);
    println!("Largest: {:?}", largest);
    
    println!("Smallest: {}", smallest.as_deref().unwrap_or("none string"));
    println!("Largest: {}", largest.as_deref().unwrap_or("none string"));
}


     
/*
run:
  
Smallest: Some("is")
Largest: Some("memory-efficient")
Smallest: is
Largest: memory-efficient
  
*/

 



answered Dec 27, 2024 by avibootz
edited Dec 27, 2024 by avibootz

Related questions

...