Thursday, December 7, 2023
HomeSoftware EngineeringEasy methods to Reverse a String in Golang

Easy methods to Reverse a String in Golang


The problem

Full the answer in order that it reverses the string handed into it.

'world'  =>  'dlrow'
'phrase'   =>  'drow'

The answer in Golang

Choice 1:

package deal resolution
func Answer(phrase string) (out string) {
  for _, v := vary phrase {
    out = string(v) + out
  }
  return
}

Choice 2:

package deal resolution
import "strings"
func Answer(phrase string) string {    
    var b strings.Builder
    for i:=len(phrase)-1; i>-1; i-- {
      b.WriteByte(phrase[i])      
    }
    return b.String()
}

Choice 3:

package deal resolution
import "strings"
func Answer(phrase string) string {
  var reversed []string
  for i := vary(phrase) {
    reversed = append(reversed, string(phrase[len(word)-1-i]))
  }
  return strings.Be a part of(reversed, "")
}

Take a look at instances to validate our resolution

package deal solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
var _ = Describe("Take a look at Instance", func() {
  It("ought to take a look at that the answer returns the proper worth", func() {
    Anticipate(Answer("world")).To(Equal("dlrow"))
    Anticipate(Answer("hi there")).To(Equal("olleh"))
    Anticipate(Answer("")).To(Equal(""))
    Anticipate(Answer("h")).To(Equal("h"))
  })
})
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments