在句子中获取单词的第一个字母

ysK*_*nok 3 string iterator text-manipulation rust

我怎么能从句子中得到第一个字母; 例如:"Rust是一种快速可靠的编程语言"应该返回输出riafrpl.

fn main() {
    let string: &'static str = "Rust is a fast reliable programming language";
    println!("First letters: {}", string);
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*all 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
Run Code Online (Sandbox Code Playgroud)

  • 你为什么不使用`split_whitespace()`? (3认同)
  • @Boiethios因为我没想到它!这也将消除ljedrz答案中可能出现的恐慌. (2认同)
  • 我必须说,使用`flat_map`来利用`Option`的`IntoIterator`功能是我从未考虑过的. (2认同)

lje*_*drz 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
}
Run Code Online (Sandbox Code Playgroud)