str := "This is a string with spaces"
words := strings.Split(str, " ")
key := strings.ToLower(words[0])
for _, word := range words[1:] {
key += strings.Title(word)
}
log.Println(key)
func camelCase(s string) string {
// Remove all characters that are not alphanumeric or spaces or underscores
s = regexp.MustCompile("[^a-zA-Z0-9_ ]+").ReplaceAllString(s, "")
// Replace all underscores with spaces
s = strings.ReplaceAll(s, "_", " ")
// Title case s
s = cases.Title(language.AmericanEnglish, cases.NoLower).String(s)
// Remove all spaces
s = strings.ReplaceAll(s, " ", "")
// Lowercase the first letter
if len(s) > 0 {
s = strings.ToLower(s[:1]) + s[1:]
}
return s
}
3条答案
按热度按时间8yoxcaq71#
我个人喜欢使用https://github.com/iancoleman/strcase库
6uxekuva2#
如果只处理空格,可以避免正则表达式。请参阅
strings
包,以获得可用于扩展此功能的有用助手:dxpyg8gm3#
我认为现有的两个答案有一些问题,所以我写了一个自定义函数。
我一直在使用一个利用字符串的解决方案.Title(),如@sam-berry,但从go1.18(2022年3月15日)起已被弃用。@david-yappeter的答案中的库似乎没有使用该函数,但如果字符串包含任何unicode,它可能会表现得很糟糕。
由于strings.Title()弃用语句要求使用cases包,因此我编写了这个函数,它删除了任何有问题的字符,如Unicode或标点符号,将下划线视为空格,并使用cases.Title().String()进行大小写处理。