ToLower
, ToUpper
There are lowercase and uppercase letters. To change from one to the other, we can use functions from the strings package in Go.
The strings.ToLower
and ToUpper
funcs have the expected results. They do not change characters like digits, spaces, or punctuation. Title()
capitalizes all words.
ToLower
exampleLet us begin with strings.ToLower
. We have a string
literal with the value of "Name." When we call ToLower
, a new string
is returned.
string
.string
(value) is left alone after strings.ToLower
returns.fmt.Println
. The string
was lowercased.package main import ( "fmt" "strings" ) func main() { value := "Name" // Convert to lowercase. valueLower := strings.ToLower(value) fmt.Println("BEFORE:", value) fmt.Println("AFTER: ", valueLower) }BEFORE: Name AFTER: name
ToUpper
exampleThe ToUpper
func
works in the same way as ToLower
. It returns a new, copied version of the string
argument that has lowercase chars changed to uppercase ones.
package main import ( "fmt" "strings" ) func main() { value := "Dot Net Perls" // Use ToUpper. valueUpper := strings.ToUpper(value) fmt.Println("BEFORE:", value) fmt.Println("AFTER: ", valueUpper) }BEFORE: Dot Net Perls AFTER: DOT NET PERLS
The strings package provides ways to change the case of characters. Here we apply title-casing to a string
with the Title func
. The result is a properly-capitalized string
.
package main import ( "fmt" "strings" ) func main() { name := "the apology" // Capitalize this string. result := strings.Title(name) fmt.Println(result) }The Apology
For real-world programs in Go, we often need methods like strings.ToLower
and ToUpper
. These can help us simplify our programs (as by using only lowercase-based logic).