...

/

Solution Review: Reverse a String

Solution Review: Reverse a String

This lesson discusses the solution to the challenge given in the previous lesson.

We'll cover the following...
Press + to interact
package main
import "fmt"
// variant: use of slice of byte and conversions
func reverse1(s string) string {
sl := []byte(s)
var rev [100]byte
j := 0
for i:=len(sl)-1; i >= 0; i-- {
rev[j] = sl[i]
j++
}
strRev := string(rev[:len(sl)])
return strRev
}
// variant: "in place" using swapping _one slice
func reverse2(s string) string {
sl2 := []byte(s)
for i, j := 0, len(sl2) - 1; i < j; i, j = i+1, j-1 {
sl2[i], sl2[j] = sl2[j], sl2[i]
}
return string(sl2)
}
//variant: using [] int for runes (necessary for Unicode-strings!):
func reverse3(s string) string {
runes := []rune(s)
n, h := len(runes), len(runes)/2
for i:= 0; i < h; i ++ {
runes[i], runes[n-1-i] = runes[n-1-i], runes[i]
}
return string(runes)
}
func main() {
// reverse a string:
str := "Google"
fmt.Printf("The reversed string using variant 1 is -%s-\n", reverse1(str))
fmt.Printf("The reversed string using variant 2 is -%s-\n", reverse2(str))
fmt.Printf("The reversed string using variant 3 is -%s-\n", reverse3(str))
}

In the above code, there are three basic functions: reverse1, reverse2, and reverse3. Let’s study them one by one.

1st Variant

Look at the header of function reverse1 at line 5: func reverse1(s string) string. It takes a string s as a parameter to reverse it and returns the reversed string. This variant is the implementation of a slice of bytes, converting it later into a string.

At line 6, we make a slice of bytes sl, containing all the elements from string s passed to the function reverse1. Next, we make an array rev of byte type of length 100 (assuming that the length of the string s doesn’t exceed 100). At line 8, we make an iterator j that we will use to traverse through the rev array as we move forward, filling rev with values.

Then we have a ...