How to Capitalize First Letter in Golang

Here are three ways to capitalize the first letter in Go:

  1. Using strings.Title() method
  2. Using byte slice
  3. Using unicode.ToUpper() method

Method 1: Using strings.Title() method

Diagram of Using strings.Title() method

Go strings.Title() method is used to capitalize the first letter of each word in a given string. It returns a new string with all the first letters of words in the input string capitalized and all other characters in lowercase.

Example

package main

import (
  "fmt"
  "strings"
)

func main() {
  str := "We are the world"
  title := strings.Title(str)
  fmt.Println(title)
}

Output

We Are The World

Method 2: Using a byte slice

Here is the step-by-step guide:

  1. Convert the string to a byte slice.
  2. Check if the first character is a lowercase letter.
  3. If it is, subtract 32 from its ASCII value to convert it to an uppercase letter (this works for English letters only).
  4. Convert the byte slice back to a string.

Example

package main

import (
  "fmt"
)

func capitalizeByteSlice(str string) string {
  bs := []byte(str)
  if len(bs) == 0 {
    return ""
  }
  bs[0] = byte(bs[0] - 32)
  return string(bs)
}

func main() {
  str := "hello"
  fmt.Println(capitalizeByteSlice(str))
}

Output

Hello

Method 3: Using unicode.ToUpper()

Diagram of Using unicode.ToUpper()

Go unicode.ToUpper() function can be used to convert the first letter of a string to uppercase.

Example

package main

import (
  "fmt"
  "unicode"
)

func capitalize(str string) string {
  runes := []rune(str)
  runes[0] = unicode.ToUpper(runes[0])
  return string(runes)
}

func main() {
  word := "we are the world"
  fmt.Println(capitalize(word))
}

Output

We are the world

Conclusion

Use the “strings.Title()” method to convert every word’s first letter to be capitalized in Go.

Use the “unicode.ToUpper()” method to convert the first letter of the word of the sentence in Go.