0

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)
}
Alireza
  • 6,497
  • 13
  • 59
  • 132

1 Answers1

1

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.

For the sake of your example, however, (since your string is just one word) see the Title method from the strings package.

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 ""
}
jonroethke
  • 1,152
  • 2
  • 8
  • 16