转到版本
go version go1.16.7 linux/amd64
问题
我正在经历一个关于创建首字母缩略词的练习,我选择用正则表达式来做。
给我的一些测试用例如下:
input: "Ruby on Rails",
expected: "ROR"
input: "GNU Image Manipulation Program",
expected: "GIMP"
input: "Complementary metal-oxide semiconductor",
expected: "CMOS"
input: "Something - I made up from thin air",
expected: "SIMUFTA"
input: "Halley's Comet",
expected: "HC"
input: "The Road _Not_ Taken",
expected: "TRNT"
下面的代码能够通过许多简单的测试,如果第一个字母是大写的,那么提取该字母并从中制作一个首字母缩略词
Portable Network Graphics -> PNG
法典
// Package acronym creates an acronym based on Capitalized Letters
package acronym
import (
"regexp"
"strings"
)
// Abbreviate: creates an acronym for a full form string
func Abbreviate(s string) string {
re := regexp.MustCompile(`\b[A-Za-z]`)
abbreviation := strings.Join(re.FindAllString(s, -1), "")
return strings.ToUpper(abbreviation)
}
我唯一失败的测试是
=== RUN TestAcronym
acronym_test.go:11: Acronym test [Halley's Comet], expected [HC], actual [HSC]
acronym_test.go:11: Acronym test [The Road _Not_ Taken], expected [TRNT], actual [TRT]
--- FAIL: TestAcronym (0.00s)
正则表达式101 儿童游乐场
我无法弄清楚如何仅编译 for 测试用例并在测试用例中获取 。HCHalley's CometNThe Road _Not_ Taken
我必须保留小写字符的原因之一是因为大小写,也因为某些测试用例中的其他小写字符[a-z]Complementary metal-oxide semiconductor
我实际上可以删除诸如正则表达式编译之类的字符,但我认为这不会使我的函数更加通用(而是通过测试)-_
我想知道如何删除字符,以使首字母缩略词功能更强大?'_
繁星coding
回首忆惘然
随时随地看视频慕课网APP
相关分类