Learn How to reverse a string in Golang
Posted on: December 09, 2021 by Deven
In this article, you will learn about how to reverse a string in the Go language.
Reverse a string means printing a given string from the backward. Like, the first letter of a given string to the last and last one into the first and so on. You can perform this action in Go language easily.
Let’s imagine you have a given string that is “morning” and now you want to reverse it as “gninrom”. You can simply do it in Go language. See the code example below:
package main
import "fmt"
func reverse(s string) string {
rns := []rune(s)
for i, j := 0, len(rns)-1; i < j; i, j = i+1, j-1 {
rns[i], rns[j] = rns[j], rns[i]
}
return string(rns)
}
func main() {
str := "morning"
strRev := reverse(str)
fmt.Println(str)
fmt.Println(strRev)
}
// Output :
// morning
// gninrom
You can also perform the same action by declaring an empty string and appending them from last to first. Let’s see the below code example to make things more clear to you:
package main
import "fmt"
func reverse(str string) (result string) {
for _, v := range str {
result = string(v) + result
}
return
}
func main() {
str := "morning"
strRev := reverse(str)
fmt.Println(str)
fmt.Println(strRev)
}
// Output:
// morning
// gninrom
Like reversing a single word, you can also reverse multiple words. For example, you have an array of three fruits "apple, banana, orange" and you want to reverse them as " orange, banana, apple". It is also possible in Go language. To do so, we have to convert these strings into an array of strings and then simply apply the reverse loop. See the code example below:
package main
import (
"fmt"
"strings"
)
func reverse_words(s string) string {
words := strings.Fields(s)
for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 {
words[i], words[j] = words[j], words[i]
}
return strings.Join(words, " ")
}
func main() {
fmt.Println("apple banana orange")
fmt.Println(reverse_words("apple banana orange"))
}
// Output:
// apple banana orange
// orange banana apple
This is all about reversing a string in the Go language.
Share on social media
//