Search code examples
stringrustiteratortext-manipulation

Get the first letters of words in a sentence


How I could get the first letters from a sentence; example: "Rust is a fast reliable programming language" should return the output riafrpl.

fn main() {
    let string: &'static str = "Rust is a fast reliable programming language";
    println!("First letters: {}", string);
}

Solution

  • let initials: String = string
        .split(" ")                     // create an iterator, yielding words
        .flat_map(|s| s.chars().nth(0)) // get the first char of each word
        .collect();                     // collect the result into a String