Acronym

1. Readme

缩写

将短语转换为,其首字母缩写词。

技术人员都喜欢他们的 TLA(三字母缩略语(Three Letter Acronyms)显得高大上)!

通过编写将诸如 Portable Network Graphics 之类的长名称,转换为其首字母缩略词(PNG)的程序,帮助生成一些术语。

资源

Julien Vanierhttps://github.com/monkbroc

2. 开始你的表演

pub fn abbreviate(phrase: &str) -> String {
   unimplemented!("Given the phrase '{}', return its acronym", phrase);
}

3. 测试代码查看


# #![allow(unused_variables)]
#fn main() {
#[test]
fn empty() {
   assert_eq!(abbreviate(""), "");
}

#[test]
//#[ignore]
fn basic() {
   assert_eq!(abbreviate("Portable Network Graphics"), "PNG");
}

#[test]
//#[ignore]
fn lowercase_words() {
   assert_eq!(abbreviate("Ruby on Rails"), "ROR");
}

#[test]
//#[ignore]
fn camelcase() {
   assert_eq!(abbreviate("HyperText Markup Language"), "HTML");
}

#[test]
//#[ignore]
fn punctuation() {
   assert_eq!(abbreviate("First In, First Out"), "FIFO");
}

#[test]
//#[ignore]
fn all_caps_words() {
   assert_eq!(abbreviate("PHP: Hypertext Preprocessor"), "PHP");
}

#[test]
//#[ignore]
fn non_acronym_all_caps_word() {
   assert_eq!(abbreviate("GNU Image Manipulation Program"), "GIMP");
}

#[test]
//#[ignore]
fn hyphenated() {
   assert_eq!(
       abbreviate("Complementary metal-oxide semiconductor"),
       "CMOS"
   );
}

#}

4. 答案


# #![allow(unused_variables)]
#fn main() {
pub fn abbreviate(phrase: &str) -> String {
   phrase
       .split(|c: char| c.is_whitespace() || !c.is_alphanumeric())
       .flat_map(|word| split_camel(word))
       .filter_map(|word| word.chars().next())
       .collect::<String>()
       .to_uppercase()
}

fn split_camel(phrase: &str) -> Vec<String> {
   let chars: Vec<char> = phrase.chars().collect();
   let mut words: Vec<String> = Vec::new();
   let mut word_start: usize = 0;
   for (i, c) in chars.iter().enumerate() {
       if i == chars.len() - 1 || c.is_lowercase() && chars[i + 1].is_uppercase() {
           words.push(chars[word_start..i + 1].iter().cloned().collect());
           word_start = i + 1;
       }
   }
   words
}

#}



填充/相关