How to UpperCase the start of each Word in a String in Golang

The challenge

The task is to take a string of lower-cased words and convert the sentence to upper-case the first letter/character of each word


this is the sentence would be This Is The Sentence

The solution in Golang

Option 1:

As a first approach, we could loop through each word, and Title it before adding it back to a new string. Then make sure to trim any spaces before returning it.

package solution import "strings" func ToTitleCase(str string) string { s := "" for _, word := range strings.Split(str, " ") { s += strings.Title(word)+" " } return strings.TrimSpace(s) }
Code language: Go (go)

Option 2:

This could be dramatically simplified by just using the Title method of the strings module.

package solution import "strings" func ToTitleCase(str string) string { return strings.Title(str) }
Code language: Go (go)

Option 3:

Another option would be to perform a loop around a Split and Join instead of trimming.

package solution import "strings" func ToTitleCase(str string) string { words := strings.Split(str, " ") result := make([]string, len(words)) for i, word := range words { result[i] = strings.Title(word) } return strings.Join(result, " ") }
Code language: Go (go)

Test cases to validate our solution

package solution_test import ( . "" . "" ) var _ = Describe("Test Example", func() { It("should work for sample test cases", func() { Expect(ToTitleCase("most trees are blue")).To(Equal("Most Trees Are Blue")) Expect(ToTitleCase("All the rules in this world were made by someone no smarter than you. So make your own.")).To(Equal("All The Rules In This World Were Made By Someone No Smarter Than You. So Make Your Own.")) Expect(ToTitleCase("When I die. then you will realize")).To(Equal("When I Die. Then You Will Realize")) Expect(ToTitleCase("Jonah Hill is a genius")).To(Equal("Jonah Hill Is A Genius")) Expect(ToTitleCase("Dying is mainstream")).To(Equal("Dying Is Mainstream")) }) })
Code language: Go (go)
Notify of
Inline Feedbacks
View all comments