stringgotitle-case

Make first letter of words uppercase in a string


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.


Solution

  • === DEPRECATION NOTICE ===
    The rule Title uses for word boundaries does not handle Unicode punctuation properly.

    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