Reverse a string using for or range keyword in Go programming language.
For example, stressed will become desserts after reversed.
Run Code on Go Playground
func Reverse(s string) (rs string) {
for _, runeValue := range s {
rs = string(runeValue) + rs
}
return
}
for loop iteration
Run Code on Go Playground
import "unicode/utf8"
func Reverse(s string) (rs string) {
for i, w := 0, 0; i < len(s); i += w {
r, width := utf8.DecodeRuneInString(s[i:])
w = width
rs = string(r) + rs
}
return
}
Tested on: The Go Playground
References: