Make first letter of words uppercase in a string

There is a function in the built-in strings package called Title.

s := "INTEGRATED ENGINEERING 5 Year (BSC with a Year in Industry)"
fmt.Println(strings.Title(strings.ToLower(s)))

https://go.dev/play/p/THsIzD3ZCF9


The below is an alternate to the accepted answer, which is now deprecated:

package main

import (
    "fmt"
    "golang.org/x/text/cases"
    "golang.org/x/text/language"
)

func main() {
    msg := "INTEGRATED ENGINEERING 5 Year (BSC with a Year in Industry)"
    fmt.Println(cases.Title(language.English, cases.Compact).String(msg))
}

You can use regular expressions for this task. A \w+ regexp will match all the words, then by using Regexp.ReplaceAllStringFunc you can replace the words with intended content, skipping stop words. In your case, strings.ToLower and strings.Title will be also helpful.

Example:

str := "INTEGRATED ENGINEERING 5 Year (BSC with a Year in Industry)"

// Function replacing words (assuming lower case input)
replace := func(word string) string {
    switch word {
    case "with", "in", "a":
        return word
    }
    return strings.Title(word)
}

r := regexp.MustCompile(`\w+`)
str = r.ReplaceAllStringFunc(strings.ToLower(str), replace)

fmt.Println(str)

// Output:
// Integrated Engineering 5 Year (Bsc with a Year in Industry)

https://play.golang.org/p/uMag7buHG8

You can easily adapt this to your array of strings.

Tags:

Go