golang

Examples on How to Capitalize the First Letter of Words in Golang

In Go programming, there are specific scenarios where we need to capitalize the first letter of words within a string. Capitalizing the first letter of each word can be beneficial for formatting text, generating titles, or enhancing the presentation of user input. This article explores the various examples and techniques in Go to capitalize the first letter of words within a string. We will examine the different approaches, ranging from simple built-in functions to more customized implementations.

Example 1: Capitalize the First Word of the Letter Using the ToUpper() Function

The basic example of transforming the first letter of the string into the uppercase is given in the following. Consider the following program of transforming the first letter of the provided word:

package main
import (
  "fmt"
  "unicode"
)
func ToCapital(MyStr string) string {
  runes := []rune(MyStr)
  runes[0] = unicode.ToUpper(runes[0])
  return string(runes)
}
func main() {
  text := "happy Life"
  fmt.Println(ToCapital(text))
}

We include the Unicode package inside the import section to work with Unicode characters. Then, we employ the ToCapital() function which takes the “MyStr” string as an argument and returns a modified string with the capitalized first letter.

Inside the function, the “MyStr” string is converted into a slice of runes (Unicode characters) using []rune(MyStr). Next, the first rune in the runes slice corresponding to the first letter of the string is capitalized using the unicode.ToUpper(runes[0]). The unicode.ToUpper() function converts a lowercase character to its uppercase equivalent. The capitalized rune is then assigned back to the first position in the runes slice.

Finally, the modified runes slice is converted back to a string using the string(runes) and is returned from the function. After that comes the main function where we set the string variable “text” to “happy Life” as its first value. Then, the ToCapital() function is called with text as an argument which capitalizes the first letter of the string.

The output displays the first value of the string in upper case using the ToCapital() function:

Example 2: Capitalize the First Word of the Letter Using the Strings.Title() Function

Although, the stringsTitle() method, which is an obvious and straightforward approach, can be used to uppercase the first letter of any word in a string. It utilizes the rules of Unicode title case mapping.

package main
import (
    "fmt"
    "strings"
)

func main() {
    result := strings.Title("example title")
    fmt.Println(result)
}

We import the additional “strings” package for string manipulation functions here in the program. After that, we employ the main() function where the strings.Title() function is called with the “example title” argument. When a string is passed to the strings.Title() function, a new string is created that capitalizes the initial letter of every single word. It uses the rules of the Unicode title case mapping. The result of the strings.Title() function is assigned to the variable result.

As observed in the following output, the strings.Title() function capitalizes the initial letter of both the words on the console:

Example 3: Capitalize the First Word of the Letter Using the Byte Slice

Here is an additional method to capitalize the initial letter of a text in Go using a byte slice. The subsequent code illustrates the capitalization of the first letter using the byte slice.

package main
import (
  "fmt"
)
func ByteSliceCapital(s1 string) string {
  byteSlice := []byte(s1)
  if len(byteSlice) == 0 {
    return ""
  }
  byteSlice[0] = byte(byteSlice[0] - 32)
  return string(byteSlice)
}
func main() {
  s1 := "programming"
  fmt.Println(ByteSliceCapital(s1))
}

We define the ByteSliceCapital() function which inputs the “s1” string as an argument and returns a modified string with the capitalized first letter. Inside the function, the “s1” string is converted into a byte slice using []byte(s1). Go’s byte type enables the manipulation of single characters; therefore, this is performed. If the byte slice’s length is 0, the function ensures that it is. If so, the method provides an empty string because an empty string was passed in.

Next, the first byte in the byteSlice is transformed into the capital letter by subtracting 32 from its value (byteSlice[0] – 32). In ASCII encoding, the difference between lowercase and uppercase letters is 32. We modify the byte which is then assigned back to the first position in the byteSlice. Finally, the modified byteSlice is converted back to a string using the string(byteSlice) and is returned from the function.

After that, we have a string variable “s1” which is initialized with the “programming” value in the main() function. Then, the ByteSliceCapital function is deployed with “s1” as an argument which capitalizes the first letter of the string using byte manipulation.

Thus, the output shows the first letter of the specified string in the upper case by manipulating the underlying byte slice:

Example 4: Capitalize the First Word of the Letter Using the ToUpper() Function with the Loop

However, we can also capitalize the first letter of a string using the function of the Unicode package ToUpper() function to handle the Unicode characters. The following code demonstrates it more efficiently:

import (
    "fmt"
    "unicode"
)
func main() {
    MyString := "hey, team!"
    fmt.Println("Original string:", MyString)
    var res []rune
    isText := true
    for _, value := range MyString {

      if isText && unicode.IsLetter(value) {

          res = append(res, unicode.ToUpper(value))

          isText = false

      } else if !unicode.IsLetter(value) {

          isText = true

          res = append(res, value)

      } else {

         res = append(res, value)

        }

      }

      fmt.Println("String capitalization is:")
     
      fmt.Println(string(res))

}

We begin with the program’s main() function where the “MyString” string variable is initialized with the “hey, team!” value. Then, we declare the “res” slice of runes (Unicode characters) to store the modified string. We then initially set the “isText” Boolean variable to true to indicate that the next encountered character is part of a word. The “MyString” string’s individual characters are iterated over by the “for” loop.

Inside the loop, we examine if the “isText” is true and if the character is a letter using unicode.IsLetter(value). If both conditions are met, the character is capitalized using the unicode.ToUpper(value) and is appended to the “res” slice.

Additionally, the subsequent character is marked as not being a word by setting the “isText” property to false. If both conditions are met, the character is capitalized using unicode.ToUpper(value) and is appended to the “res” slice. The following character will be part of a word if the present one is not a letter, which causes the “isText” property to be set to true. The character is appended to the “res” slice as it is. If the character is a letter but not the first letter of a word, it is simply appended to the “res” slice.

Hence, the final result includes both the initial string and the capitalization of each word’s first letter:

Conclusion

We can utilize the techniques and examples provided in this article to easily capitalize the first letter of words in Go whether we prefer the ToCapital() method, strings.Title() method, and ToUpper() method of the Unicode package. We now have the knowledge and examples of effectively capitalizing the first letter of words in Go programs.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content