How to get the first word from a string in Rust

2 Answers

0 votes
fn main() {
    let s = "rust javascript php c c++ python";
    
    if let Some(index) = s.find(' ') {
        println!("{}", &s[..index]);
    }
}


  
/*
run:

rust

*/

 



answered Sep 19, 2024 by avibootz
0 votes
fn main() {
    let s = "rust javascript php c c++ python";
    
    let first_word = s
    .split_whitespace()
    .next()
    .unwrap_or("");

    println!("{}", first_word);
}


  
/*
run:

rust

*/

 



answered Sep 19, 2024 by avibootz
...