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.
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 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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With