How to get the length of the last word in a string with Rust

1 Answer

0 votes
fn length_of_last_word(s: &str) -> usize {
    let words: Vec<&str> = s.split_whitespace().collect();
    
    match words.last() {
        Some(word) => word.len(),
        None => 0,
    }
}

fn main() {
    let str = "rust java c javascript golang";
    
    println!("The length of the last word is: {}", length_of_last_word(str));
}


  
/*
run:

The length of the last word is: 6

*/

 



answered Sep 9, 2024 by avibootz
...