Reputation: 41
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
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
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