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
  • 5,659
  • 11
  • 52
  • 118

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,052
  • 2
  • 8
  • 16
  • `Title()` does not capitalize the first letter of a string--it capitalizes the first letter of each word. – Flimzy Jul 24 '19 at 07:31
  • Good point, it was fine for the sake of his example but would fail in other cases with multi-word strings. Thanks, edited – jonroethke Jul 24 '19 at 13:48