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.

5 Answers

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

6

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) 

You can easily adapt this to your array of strings.

1

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

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

In Go 1.18 strings.Title() is deprecated.

Here you can read the following to know what to use now

you should use cases.Title instead.

Well you didn't specify the language you're using, so I'll give you a general answer. You have an array with a bunch of strings in it. First I'd make the entire string lower case, then just go through each character in the string (capitalize the first one, rest stay lower case). At this point you need to look for the space, this will help you divide up the words in each string. The first character after finding a space is obviously a different word and should be capitalized. You can verify the next word isn't and in with Or a as well.

I'm not at a computer so I can't give to a specific example, but I hope this gets to in the right direction at least

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.