3

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);
}
Peter Hall
  • 53,120
  • 14
  • 139
  • 204
ysKnok
  • 41
  • 5

2 Answers2

9
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
Peter Hall
  • 53,120
  • 14
  • 139
  • 204
6

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
}
ljedrz
  • 20,316
  • 4
  • 69
  • 97