How to remove the last word from a string with Rust

2 Answers

0 votes
fn main() {
    let s = "rust c c++ rust python java rust";
    
    let last_space_index = s.rfind(' ').unwrap();
    let s = &s[..last_space_index];
    
    println!("{}", s);
}


  
/*
run:

rust c c++ rust python java

*/

 



answered Sep 6, 2024 by avibootz
0 votes
fn remove_last_word(s: &str) -> String {
    // Trim trailing whitespace
    let trimmed = s.trim_end();

    // Find last space
    if let Some(pos) = trimmed.rfind(' ') {
        trimmed[..pos].to_string()
    } else {
        trimmed.to_string()
    }
}

fn main() {
    let mut s;

    s = "c c++ c# java python";
    println!("1. {}", remove_last_word(s));

    s = "";
    println!("2. {}", remove_last_word(s));

    s = "c";
    println!("3. {}", remove_last_word(s));

    s = "c# java python ";
    println!("4. {}", remove_last_word(s));

    s = "  ";
    println!("5. {}", remove_last_word(s));
}



/*
run:

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

*/

 



answered Mar 27 by avibootz
...