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

1 min read 283 words

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

Example:

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)
}

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)
}

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, " ")
}

Test cases to validate our solution

package solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
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"))
  })
})
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts