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(' ').

Examples:

// => returns "StRiNg"
toWeirdCase("String")

// => returns "WeIrD StRiNg CaSe"
toWeirdCase("Weird string case")

The solution in Golang

Option 1:

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

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[0]))+strings.ToLower(string(m[1:]))})
}

Option 3:

package solution
import "unicode"
func toWeirdCase(str string) string {
  chars := []rune{}
  for _, r := range str {
    if len(chars) == 0 || !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)
}

Test cases to validate our solution

package solution
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
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"))
  })
})