If we want to index a character in Go, we can convert a string to an array or rune. A rune is basically a Unicode point. A Unicode point refers to a numerical value representing a Unicode character.
This brief article will learn how to reverse a string in Go by first converting it into an array of runes.
Reverse String – Rune by Rune
Consider the example program below:
import (
"fmt"
)
func main() {
str := "Hello"
rune_arr := []rune(str)
var rev []rune
for i := len(rune_arr) - 1; i >= 0; i-- {
rev = append(rev, rune_arr[i])
}
fmt.Println("Reverse: ", string(rev))
}
In the example above, we start by converting the string “str” to an array of rune. Doing so allows us to index individual characters in the string.
Once we have the index of individual characters, we append each character to a new string starting from the end to start.
The resulting output is the string in reverse order, as:
Reverse String – Byte
As mentioned, a string is a sequence of bytes. Hence, we can create the reverse of a string by reversing each byte at a time.
Take the example below:
var byte strings.Builder
byte.Grow(len(s))
for i := len(s) - 1; i >= 0; i-- {
byte.WriteByte(s[i])
}
return byte.String()
}
The above example converts a string by reversing it byte by byte.
Conclusion
This article shows you how to reverse a string in the go programming language.
Keep practicing!