Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 649
Conor Avatar asked Nov 13 '15 15:11

Conor


People also ask

How do you replace the first character in a string with uppercase?

You can use str. title() to get a title cased version of the string. This converts the first character of each word in the string to uppercase and the remaining characters to lowercase.

How do you uppercase the first letter of a string in python?

How do you capitalize the first letter of a string? The first letter of a string can be capitalized using the capitalize() function. This method returns a string with the first letter capitalized. If you are looking to capitalize the first letter of the entire string the title() function should be used.

How do you convert the first letter of string to uppercase in TypeScript?

To capitalize the first letter of a string in TypeScript:Use the charAt() method to get the first letter of the string. Call the toUpperCase() method on the letter. Use the slice() method to get the rest of the string. Concatenate the results.


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

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

like image 180
boug Avatar answered Sep 22 '22 12:09

boug


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.

like image 32
tomasz Avatar answered Sep 23 '22 12:09

tomasz