How to remove the middle word from a string in Rust

1 Answer

0 votes
fn remove_middle_word(s: &str) -> String {
    // Split the string into words
    let words: Vec<&str> = s.split_whitespace().collect();
    
    // Calculate the middle index
    let middle_index = words.len() / 2;
    
    // Create a new string without the middle word
    let result: Vec<&str> = words[..middle_index].iter()
                            .chain(&words[middle_index + 1..])
                            .cloned().collect();
    
    result.join(" ")
}

fn main() {
    let str = "c# c c++ java rust";
    
    println!("{}", remove_middle_word(str));
}



   
/*
run:
  
c# c java rust
  
*/

 



answered Dec 4, 2024 by avibootz
...