I need to implement the capitalize method of python in Go. I know that first I have to lowercase it and then use toTitle
on it. Have a look at the sample code :
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)
}
In Python, the capitalize()
method converts the first character of a string to capital (uppercase) letter.
If you are seeking to do the same with Go, you can range over the string contents, then leverage the unicode
package method ToUpper to convert the first rune in the string to uppercase, then cast it to a string, then concatenate that with the rest of the original string.
example:
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 ""
}