How to get the last word from a string in Rust

2 Answers

0 votes
fn get_last_word(s: &str) -> Option<&str> {
    s.split_whitespace().last()
}

fn main() {
    let my_string = "Rust has friendly compiler with useful error messages";

    if let Some(last_word) = get_last_word(my_string) {
        println!("The last word is: {}", last_word);
    } else {
        println!("No words found.");
    }
}

 

/*
run:

The last word is: messages

*/

 



answered Jan 4, 2025 by avibootz
edited Mar 27 by avibootz
0 votes
fn get_last_word(input: &str) -> String {
    // Trim leading/trailing whitespace
    let trimmed = input.trim();

    // If empty after trimming, return empty string
    if trimmed.is_empty() {
        return String::new();
    }

    // Split on whitespace and return the last piece
    trimmed
        .split_whitespace()
        .last()
        .unwrap_or("")
        .to_string()
}

fn main() {
    let tests = [
        "vb.net javascript php c c++ python c#",
        "",
        "c#",
        "c c++ java ",
        "  ",
    ];

    for (i, t) in tests.iter().enumerate() {
        println!("{}. {}", i + 1, get_last_word(t));
    }
}



/*
run:

1. c#
2. 
3. c#
4. java
5. 

*/

 



answered Mar 27 by avibootz
...