How to find the length of the second smallest word in a string with Rust

1 Answer

0 votes
fn second_smallest_word_length(string: &str) -> i32 {
    let arr: Vec<&str> = string.split_whitespace().collect();
    
    if arr.len() < 2 {
        return -1;
    }
    
    let mut lengths: Vec<usize> = arr.iter().map(|word| word.len()).collect();
    lengths.sort();
    
    lengths[1] as i32
}

fn main() {
    let str = "c# rust c++ python javascript";
    
    println!("{}", second_smallest_word_length(str));
}

  
    
/*
run:
  
3
  
*/

 



answered Oct 4, 2024 by avibootz

Related questions

1 answer 95 views
1 answer 106 views
1 answer 118 views
2 answers 145 views
1 answer 223 views
...