Skip to content

How to Alternate String Casing in Golang

The challenge

Write a function toWeirdCase (weirdcase in Ruby) that accepts a string, and returns the same string with all even indexed characters in each word uppercased, and all odd indexed characters in each word lowercased. The indexing just explained is zero-based, so the zero-ith index is even, therefore that character should be uppercased and you need to start over for each word.

The passed-in string will only consist of alphabetical characters and spaces(' '). Spaces will only be present if there are multiple words. Words will be separated by a single space(' ').


// => returns "StRiNg" toWeirdCase("String") // => returns "WeIrD StRiNg CaSe" toWeirdCase("Weird string case")
Code language: JavaScript (javascript)

The solution in Golang

Option 1:

package solution import "strings" func toWeirdCase(str string) string { s := "" i := for _, char := range(str) { if string(char)==" " { i= s += " " } else { if i%2== { s += strings.ToUpper(string(char)) } else { s += strings.ToLower(string(char)) } i++ } } return s }
Code language: Go (go)

Option 2:

package solution import ("regexp"; "strings") func toWeirdCase(str string) string { return regexp.MustCompile(`\w{1,2}`).ReplaceAllStringFunc(str, func(m string) string { return strings.Title(string(m[]))+strings.ToLower(string(m[1:]))}) }
Code language: Go (go)

Option 3:

package solution import "unicode" func toWeirdCase(str string) string { chars := []rune{} for _, r := range str { if len(chars) == || !unicode.IsLetter(chars[len(chars) - 1]) || unicode.IsLower(chars[len(chars) - 1]) { chars = append(chars, unicode.ToUpper(r)) } else { chars = append(chars, unicode.ToLower(r)) } } return string(chars) }
Code language: Go (go)

Test cases to validate our solution

package solution import ( . "" . "" ) var _ = Describe("Sample Test Cases:", func() { It("Should return the correct values", func() { Expect(toWeirdCase("abc def")).To(Equal("AbC DeF")) Expect(toWeirdCase("ABC")).To(Equal("AbC")) Expect(toWeirdCase("This is a test Looks like you passed")).To(Equal("ThIs Is A TeSt LoOkS LiKe YoU PaSsEd")) }) })
Code language: Go (go)

See also  How to convert a string value to an int in Go
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x