获取句子中每个单词的首字母

3

我该如何从一句话中获取每个单词的首字母呢?例如:"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);
}
2个回答

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

3
为什么你不使用 split_whitespace() - Boiethios
2
因为我没有想到!这也会消除ljedrz回答中可能出现的恐慌。 - Peter Hall
@PeterHall 是的,我忘了它可以接受多个空格! - ljedrz
2
我必须说,使用flat_map来利用OptionIntoIterator功能是我从未考虑过的事情。 - MutantOctopus

6
这是一个完美适用于Rust迭代器的任务;以下是我的做法:
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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接