Reverse a String

To reverse a string in Go language, we need to convert the string to an array of individual characters, iterate over this array, and form the reversed string.

Converting string to array of characters is tricky, and we need an understanding of how characters are stored in a string.

Each character in a string is not stored as a byte, or int, but unicode point which is a rune. So, we will convert the string into an array of rune.

Example

In the following example, we take a string in str, and reverse it.

Example.go

package main

func main() {
	str := "apple"
	chars := []rune(str)
	var result []rune
	for i := len(chars) - 1; i >= 0; i-- {
		result = append(result, chars[i])
	}
	println(string(result))
}

Output

elppa
ADVERTISEMENT

Conclusion

In this Golang Tutorial, we learned how to reverse a string in Go language using strings.Join() function, with example programs.