How to convert a string into Title Case in Golang?


Title() is a built-in function of strings package in Golang that is used to convert a string into Title Case. It converts the first character of each word in a given string into uppercase and returns the modified string.

Syntax

func Title(s string) string

Where s is the given string.

Example 1

Let us consider the following example −

package main
import (
   "fmt"
   "strings"
)
func main() {
   // Intializing the Strings
   m := "title string function"
   n := "Golang string package fUNCTION"

   // Display the Strings
   fmt.Println("String 1:", m)
   fmt.Println("String 2:", n)

   // Using the Title Function
   res1 := strings.Title(m)
   res2 := strings.Title(n)

   // Display the Title Output
   fmt.Println("\nString 1 in Title Case:", res1)
   fmt.Println("String 2 in Title Case:", res2)
}

Output

It will generate the following output −

String 1: title string function
String 2: Golang string package fUNCTION

String 1 in Title Case: Title String Function
String 2 in Title Case: Golang String Package FUNCTION

Example 2

Let us take another example −

package main
import (
   "fmt"
   "strings"
)
func main() {
   // Intializing the Strings
   x := "syed@123 123 cDE#456"
   y := "!hello! $$$$world###"
   
   // Display the Strings
   fmt.Println("String 1:", x)
   fmt.Println("String 2:", y)

   // Using the Title Function
   test1 := strings.Title(x)
   test2 := strings.Title(y)

   // Display the Title Output
   fmt.Println("\nString 1 in Title Case:", test1)
   fmt.Println("String 2 in Title Case:", test2)
}

Output

It will generate the following output −

String 1: syed@123 123 cDE#456
String 2: !hello! $$$$world###

String 1 in Title Case: Syed@123 123 CDE#456
String 2 in Title Case: !Hello! $$$$World###

Updated on: 10-Mar-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements