Saturday, December 9, 2023
HomeSoftware EngineeringLearn how to Alternate String Casing in Golang

Learn how to Alternate String Casing in Golang


The problem

Write a perform toWeirdCase (weirdcase in Ruby) that accepts a string, and returns the identical string with all even listed characters in every phrase uppercased, and all odd listed characters in every phrase lowercased. The indexing simply defined is zero-based, so the zero-ith index is even, subsequently that character ought to be uppercased and it is advisable begin over for every phrase.

The passed-in string will solely include alphabetical characters and areas(' '). Areas will solely be current if there are a number of phrases. Phrases shall be separated by a single area(' ').

Examples:

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

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

The answer in Golang

Possibility 1:

bundle resolution
import "strings"
func toWeirdCase(str string) string {
  s := ""
  i := 0
  for _, char := vary(str) {
    if string(char)==" " {
      i=0
      s += " "
    } else {
      if ipercent2==0 {
        s += strings.ToUpper(string(char))
      } else {
        s += strings.ToLower(string(char))
      }
      i++
    }
  }
  return s
}

Possibility 2:

bundle resolution
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:]))})
}

Possibility 3:

bundle resolution
import "unicode"
func toWeirdCase(str string) string {
  chars := []rune{}
  for _, r := vary 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)
}

Check instances to validate our resolution

bundle resolution
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
var _ = Describe("Pattern Check Instances:", func() {
  It("Ought to return the proper values", func() {
    Count on(toWeirdCase("abc def")).To(Equal("AbC DeF"))
    Count on(toWeirdCase("ABC")).To(Equal("AbC"))
    Count on(toWeirdCase("This can be a check Seems to be such as you handed")).To(Equal("ThIs Is A TeSt LoOkS LiKe YoU PaSsEd"))
  })
})
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments