Make first letter of words uppercase in a string

Conor picture Conor · Nov 13, 2015 · Viewed 63.7k times · Source

I have a large array of strings such as this one:

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

I want to capitalise the first letter of the words and make the rest of the words lowercase. So INTEGRATED would become Integrated.

A second spanner in the works - I want an exception to a few words such as and, in, a, with.

So the above example would become:

"Integrated Engineering 5 Year (Bsc with a Year in Industry)"

How would I do this in Go? I can code the loop/arrays to manage the change but the actual string conversion is what I struggle with.

Answer

boug picture boug · Nov 2, 2016

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