How to convert a string to camelCase in Go?

huangapple go评论88阅读模式
英文:

How to convert a string to camelCase in Go?

问题

将带有空格的字符串转换为单个驼峰命名的字符串的最简单方法是什么?

例如:"This is a string with spaces" -> "thisIsAStringWithSpaces"

英文:

What is the simplest way to convert a string with spaces to a single camelCased string?

For example: "This is a string with spaces" -> "thisIsAStringWithSpaces"

答案1

得分: 4

个人而言,我喜欢使用这个库
https://github.com/iancoleman/strcase

strcase.ToLowerCamel("This is a string with spaces")
英文:

Personally, I like to use this library
https://github.com/iancoleman/strcase

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

答案2

得分: 2

如果只处理空格,可以避免使用正则表达式。请参考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)
英文:

Can avoid regex if only dealing with spaces. See strings package for useful helpers that can be used to expand this functionality:

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)

答案3

得分: 0

我认为现有的两个答案存在一些问题,所以我编写了一个自定义函数。

我之前使用的解决方案是利用了 strings.Title(),就像 @sam-berry 所提到的那样,但是从 go1.18(2022年3月15日)开始,该函数已被弃用。@david-yappeter 的答案 中的库似乎没有使用该函数,但如果字符串包含任何 Unicode 字符,它可能会表现得不好。

由于 strings.Title() 的弃用声明建议使用 cases 包,我编写了这个函数,它会删除任何有问题的字符,比如 Unicode 或标点符号,将下划线视为空格,并使用 cases.Title().String() 进行大小写处理。

func camelCase(s string) string {
    // 删除所有非字母数字、空格或下划线的字符
    s = regexp.MustCompile("[^a-zA-Z0-9_ ]+").ReplaceAllString(s, "")

    // 将所有下划线替换为空格
    s = strings.ReplaceAll(s, "_", " ")

    // 将 s 转为标题格式
    s = cases.Title(language.AmericanEnglish, cases.NoLower).String(s)

    // 删除所有空格
    s = strings.ReplaceAll(s, " ", "")

    // 将第一个字母转为小写
    if len(s) > 0 {
        s = strings.ToLower(s[:1]) + s[1:]
    }

    return s
}
英文:

I think that the two existing answers have some issues, so I wrote a custom function instead.

I had been using a solution that leveraged strings.Title() like @sam-berry, but that has been deprecated as of go1.18 (Mar 15, 2022). The library in @david-yappeter's answer doesn't appear to use that function, but it seems like it might behave badly if the string contains any unicode.

Since the strings.Title() deprecation statement says to use the cases package, I wrote this function that removes any problematic characters like unicode or punctuation, treats underscores like spaces, and uses cases.Title().String() to do the casing.

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
}

huangapple
  • 本文由 发表于 2021年11月23日 23:48:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/70083837.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定