To reverse a string in Go, you can convert the string to a rune slice and then reverse the slice.
In this example,
str1
with a value of "Hello World"
.str1
to a rune slice.package main
import (
"fmt"
"unicode/utf8"
)
func main() {
str1 := "Hello World"
runes := []rune(str1)
for i, j := 0, utf8.RuneCountInString(str1)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
reversedStr := string(runes)
fmt.Println("Reversed string is:", reversedStr)
}
Reversed string is: dlroW olleH
In this example,
str2
with a value of "apple"
.str2
to a rune slice.package main
import (
"fmt"
"unicode/utf8"
)
func main() {
str2 := "apple"
runes := []rune(str2)
for i, j := 0, utf8.RuneCountInString(str2)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
reversedStr := string(runes)
fmt.Println("Reversed string is:", reversedStr)
}
Reversed string is: elppa
In this tutorial, we learned How to Reverse a String in Go language with well detailed examples.