Make the first letter of uppercase words in a string

I have a large array of strings like this one:

'INTEGRATED ENGINEERING 5 years (BSC with a year in the industry)'

I want to make up the first letter of words and make the rest of the words lowercase. Thus, "INTEGRATED" will become "integrated."

The second wrench is at work - I want an exception to several words, such as 'and', 'in', 'a', 'with'.

Thus, the above example will be as follows:

Integrated Engineering 5 years (Bsc with a year in industry).

How do I do this in Go? I can encode loop / arrays to control the change, but the actual conversion of the strings is what I'm struggling with.

+18
source share
3

strings Title.

, https://play.golang.org/p/07dl3hMuGH

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

https://play.golang.org/p/GLMVV10-4eX

+50

. A \w+ regexp , , Regexp.ReplaceAllStringFunc, , -. strings.ToLower strings.Title.

:

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

.

+9

, , , . . , ( , ). , . , , . , , "".

, , , ,

-11

Source: https://habr.com/ru/post/1615791/


All Articles