Golang : Humanize and Titleize functions
Humanize function takes multiple words separated by a given separator and changes them to spaces. Titleize converts a given string into a proper title with each word starting character in upper case.
Here you go!
package main
import (
"fmt"
"strings"
"unicode"
)
func Titleize(input string) (titleized string) {
isToUpper := false
for k, v := range input {
if k == 0 {
titleized = strings.ToUpper(string(input[0]))
} else {
if isToUpper || unicode.IsUpper(v) {
titleized += " " + strings.ToUpper(string(v))
isToUpper = false
} else {
if (v == '_') || (v == ' ') {
isToUpper = true
} else {
titleized += string(v)
}
}
}
}
return
}
func Humanize(input string, separator string) (humanized string) {
// Takes multiple words separated by the separator and changes them to spaces
for k, v := range input {
if k == 0 {
humanized = strings.ToUpper(string(input[0]))
} else {
if string(v) == separator {
humanized += string(" ")
} else {
humanized += string(v)
}
}
}
return
}
func main() {
// separator is _, convert to spaces
fmt.Println(Humanize("the_big_boss", "_"))
// separator is already spaces
fmt.Println(Humanize("big boss", " "))
// separator is +
fmt.Println(Humanize("big+boss", "+"))
fmt.Println(Titleize("nab that guy"))
fmt.Println(Titleize("NabThatGuy"))
fmt.Println(Titleize("space-marinesKillAliens"))
fmt.Println(Titleize("raiders_of_the_lost_ark"))
}
Output:
The big boss
Big boss
Big boss
Nab That Guy
Nab That Guy
Space-marines Kill Aliens
Raiders Of The Lost Ark
See also : Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5k Golang : Check if a word is countable or not
+9.9k Golang : Convert octal value to string to deal with leading zero problem
+8.9k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+9.6k PHP : Get coordinates latitude/longitude from string
+5.4k Golang : Display advertisement images or strings on random order
+20.8k PHP : Convert(cast) int to double/float
+18.6k Golang : Find IP address from string
+6.8k Get Facebook friends working in same company
+35k Golang : Upload and download file to/from AWS S3
+6.9k Golang : How to setup a disk space used monitoring service with Telegram bot
+18.7k Unmarshal/Load CSV record into struct in Go
+10.2k Golang : Detect number of faces or vehicles in a photo