如何在Go中将字符串转换为camelCase?

wh6knrhe  于 12个月前  发布在  Go
关注(0)|答案(3)|浏览(143)

将一个带空格的字符串转换为一个camelCased字符串的最简单的方法是什么?
举例来说:“这是一个带有空格的字符串”->“thisIsAStringWithSpaces”

8yoxcaq7

8yoxcaq71#

我个人喜欢使用https://github.com/iancoleman/strcase

strcase.ToLowerCamel("This is a string with spaces")
6uxekuva

6uxekuva2#

如果只处理空格,可以避免正则表达式。请参阅strings包,以获得可用于扩展此功能的有用助手:

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)
dxpyg8gm

dxpyg8gm3#

我认为现有的两个答案有一些问题,所以我写了一个自定义函数。
我一直在使用一个利用字符串的解决方案.Title(),如@sam-berry,但从go1.18(2022年3月15日)起已被弃用。@david-yappeter的答案中的库似乎没有使用该函数,但如果字符串包含任何unicode,它可能会表现得很糟糕。
由于strings.Title()弃用语句要求使用cases包,因此我编写了这个函数,它删除了任何有问题的字符,如Unicode或标点符号,将下划线视为空格,并使用cases.Title().String()进行大小写处理。

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
}

相关问题