我该如何从一句话中获取每个单词的首字母呢?例如:"Rust is a fast reliable programming language" 应该返回输出结果 riafrpl
。
fn main() {
let string: &'static str = "Rust is a fast reliable programming language";
println!("First letters: {}", string);
}
我该如何从一句话中获取每个单词的首字母呢?例如:"Rust is a fast reliable programming language" 应该返回输出结果 riafrpl
。
fn main() {
let string: &'static str = "Rust is a fast reliable programming language";
println!("First letters: {}", string);
}
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
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
}
split_whitespace()
? - Boiethiosflat_map
来利用Option
的IntoIterator
功能是我从未考虑过的事情。 - MutantOctopus