为什么 toTitle 在 Go 中不将小写字母大写?

Why toTitle does not capitalize a lower cased word in Go?

我需要在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中,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 ""
}