How to reverse a string in Go
Created
Modified
Using range
a range on a string returns a rune which is a codepoint.
package main
import "fmt"
func Reverse(s string) (result string) {
for _, v := range s {
result = string(v) + result
}
return
}
func main() {
// !olleH
s := Reverse("Hello!")
fmt.Println(s)
// 界世,olleH
s = Reverse("Hello,世界")
fmt.Println(s)
}
!olleH 界世,olleH
Swapping the Letters
Reverse the string by swapping the letters.
package main
import "fmt"
func Reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func main() {
// !olleH
s := Reverse("Hello!")
fmt.Println(s)
// 界世,olleH
s = Reverse("Hello,世界")
fmt.Println(s)
}
!olleH 界世,olleH