【问题标题】:Why toTitle does not capitalize a lower cased word in Go?为什么 toTitle 在 Go 中不将小写单词大写?
【发布时间】:2019-12-02 05:06:51
【问题描述】:

我需要在 Go 中实现 python 的 capitalize 方法。我知道首先我必须将其小写,然后在其上使用toTitle。看看示例代码:

package main
import (
    "fmt"
    "strings"
)

func main() {
    s := "ALIREZA"
    loweredVal:=strings.ToLower(s)
    fmt.Println("loweredVal:", loweredVal)
    toTitle := strings.ToTitle(loweredVal)
    fmt.Println("toTitle:", toTitle)
}

【问题讨论】:

标签: python go capitalize


【解决方案1】:

在 Python 中,capitalize() 方法将字符串的第一个字符转换为大写(大写)字母。

如果你想用 Go 做同样的事情,你可以对字符串内容进行范围,然后利用 unicode 包方法 ToUpper 将字符串中的第一个符文转换为大写,然后将其转换为字符串,然后将其与原始字符串的其余部分连接起来。

但是,为了您的示例,(因为您的字符串只是一个单词)请参阅 strings 包中的 Title 方法。

示例:

package main

import (
    "fmt"
    "strings"
    "unicode"
)

func main() {
    s := "ALIREZA foo bar"
    loweredVal := strings.ToLower(s)
    fmt.Println("loweredVal:", loweredVal)
    toTitle := capFirstChar(loweredVal)
    fmt.Println("toTitle:", toTitle)
}

func capFirstChar(s string) string {
    for index, value := range s {
        return string(unicode.ToUpper(value)) + s[index+1:]
    }
    return ""
}

【讨论】:

  • Title() 不将字符串的首字母大写,而是将每个单词的首字母大写。
  • 好点,为了他的例子,这很好,但在其他情况下多字串会失败。谢谢,已编辑
猜你喜欢
  • 2013-10-05
  • 1970-01-01
  • 2018-08-06
  • 2019-06-15
  • 1970-01-01
  • 2020-02-17
  • 2017-07-28
  • 2013-02-17
  • 2015-12-25
相关资源
最近更新 更多