我需要在Go中實現python的capitalize方法。我知道首先我必須將其小寫,然后再使用toTitle它??匆幌率纠a:package mainimport ( "fmt" "strings")func main() { s := "ALIREZA" loweredVal:=strings.ToLower(s) fmt.Println("loweredVal:", loweredVal) toTitle := strings.ToTitle(loweredVal) fmt.Println("toTitle:", toTitle)}
1 回答

慕標5832272
TA貢獻1966條經驗 獲得超4個贊
在 Python 中,該capitalize()
方法將字符串的第一個字符轉換為大寫字母。
如果您想用 Go 做同樣的事情,您可以遍歷字符串內容,然后利用unicode
包方法ToUpper將字符串中的第一個符文轉換為大寫,然后將其轉換為字符串,然后將其與其余部分連接起來原始字符串。
然而,為了您的示例,(因為您的字符串只是一個單詞)
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 ""
}
- 1 回答
- 0 關注
- 139 瀏覽
添加回答
舉報
0/150
提交
取消