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

问题描述 投票:3回答:2

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

fn main() {
    let string: &'static str = "Rust is a fast reliable programming language";
    println!("First letters: {}", string);
}
string rust iterator text-manipulation
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

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
}
© www.soinside.com 2019 - 2024. All rights reserved.