< 返回版块

deeptuuk 发表于 2020-04-03 15:58

Tags:rustlings

// iterators2.rs

pub fn capitalize_first(input: &str) -> String {
    let mut c = input.chars();
    match c.next() {
        None => String::new(),
        Some(first) => first.collect::<String>() + c.as_str(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Step 1.
    // Tests that verify your `capitalize_first` function implementation
    #[test]
    fn test_success() {
        assert_eq!(capitalize_first("hello"), "Hello");
    }

    #[test]
    fn test_empty() {
        assert_eq!(capitalize_first(""), "");
    }

    // Step 2.
    #[test]
    fn test_iterate_string_vec() {
        //let words = vec!["hello", "world"];
        //let capitalized_words: Vec<String> = // TODO
        //assert_eq!(capitalized_words, ["Hello", "World"]);
    }

    #[test]
    fn test_iterate_into_string() {
        //let words = vec!["hello", " ", "world"];
        //let capitalized_words = // TODO
        //assert_eq!(capitalized_words, "Hello World");
    }
}

评论区

写评论
作者 deeptuuk 2020-04-07 13:13

对以下内容的回复:

谢谢大佬!

彭亚伦 2020-04-06 07:42
fn capitalize_first(input: &str) -> String {
    let mut  c = input.chars();
    match c.next() {
        None => String::new(),
        Some(first) => std::iter::once(first.to_ascii_uppercase()).chain(c).collect()
    }
}


//step 2

let capitalized_words: Vec<String> = words.iter().map(|x| capitalize_first(x)).collect();

1 共 2 条评论, 1 页