Appearance
迭代器2: exercises/iterators/iterators2.rs
题目
rust
// iterators2.rs
//
// In this exercise, you'll learn some of the unique advantages that iterators
// can offer. Follow the steps to complete the exercise.
//
// Execute `rustlings hint iterators2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
// Step 1.
// Complete the `capitalize_first` function.
// "hello" -> "Hello"
pub fn capitalize_first(input: &str) -> String {
let mut c = input.chars();
match c.next() {
None => String::new(),
Some(first) => ???,
}
}
// Step 2.
// Apply the `capitalize_first` function to a slice of string slices.
// Return a vector of strings.
// ["hello", "world"] -> ["Hello", "World"]
pub fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
vec![]
}
// Step 3.
// Apply the `capitalize_first` function again to a slice of string slices.
// Return a single string.
// ["hello", " ", "world"] -> "Hello World"
pub fn capitalize_words_string(words: &[&str]) -> String {
String::new()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_success() {
assert_eq!(capitalize_first("hello"), "Hello");
}
#[test]
fn test_empty() {
assert_eq!(capitalize_first(""), "");
}
#[test]
fn test_iterate_string_vec() {
let words = vec!["hello", "world"];
assert_eq!(capitalize_words_vector(&words), ["Hello", "World"]);
}
#[test]
fn test_iterate_into_string() {
let words = vec!["hello", " ", "world"];
assert_eq!(capitalize_words_string(&words), "Hello World");
}
}
在本练习中,您将了解迭代器可以提供的一些独特有时。按照步骤完成练习。
题目解析
在步骤1中,变量first
是一个char
类型,我们需要将其转换为大写,并与剩余的字符进行拼接:
rust
pub fn capitalize_first(input: &str) -> String {
let mut c = input.chars();
match c.next() {
None => String::new(),
Some(first) => ???,
Some(first) => first.to_uppercase().to_string() + c.as_str(),
}
}
在步骤2中,是传递了一个数组,我们需要将数组中每个字符串的首字母都转为大写并返回,我们可以借用上一个定义的函数:
rust
pub fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
vec![]
words.iter().map(|w| capitalize_first(w)).collect()
}
步骤3,要求我们对数组中的每个元素首字母转大写,最后拼接起来:
rust
pub fn capitalize_words_string(words: &[&str]) -> String {
String::new()
words.iter().map(|w| capitalize_first(w)).collect()
}