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
+5.3k Clean up Visual Studio For Mac installation failed disk full problem
+17k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+21.8k Golang : Convert seconds to minutes and remainder seconds
+6.2k Grep : How to grep for strings inside binary data
+6.3k Golang : Embedded or data bundling example
+12.8k Swift : Convert (cast) Int to String ?
+7.5k Golang : Generate human readable password
+6.7k Golang : Decode XML data from RSS feed
+8.6k Golang : Gaussian blur on image and camera video feed examples
+8.8k Golang : Capture text return from exec function example
+13.8k Golang : Google Drive API upload and rename example