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)
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)
这对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)
| 归档时间: |
|
| 查看次数: |
307 次 |
| 最近记录: |