ysKnok
ysKnok

Reputation: 41

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);
}

Upvotes: 3

Views: 1530

Answers (2)

ljedrz
ljedrz

Reputation: 22173

This is a perfect task for Rust's iterators; here's how I would do it:

fn main() {                                                                 
    let string: &'static str = "Rust is a fast reliable programming language";

    let first_letters = string
        .split_whitespace() // split string into words
        .map(|word| word // map every word with the following:
            .chars() // split it into separate characters
            .next() // pick the first character
            .unwrap() // take the character out of the Option wrap
        )
        .collect::<String>(); // collect the characters into a string

    println!("First letters: {}", first_letters); // First letters: Riafrpl
}

Upvotes: 6

Peter Hall
Peter Hall

Reputation: 58735

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

Upvotes: 9

Related Questions