Open In App

How to Reverse a String in Golang?

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string and the task is to reverse the string. Here are a few examples.

Approach 1: Reverse the string by swapping the letters, like first with last and second with second last and so on.

Example:




// Golang program to reverse a string
package main
  
// importing fmt
import "fmt"
  
// function, which takes a string as
// argument and return the reverse of string.
func reverse(s string) string {
    rns := []rune(s) // convert to rune
    for i, j := 0, len(rns)-1; i < j; i, j = i+1, j-1 {
  
        // swap the letters of the string,
        // like first with last and so on.
        rns[i], rns[j] = rns[j], rns[i]
    }
  
    // return the reversed string.
    return string(rns)
}
  
func main() {
  
    // Reversing the string.
    str := "Geeks"
  
    // returns the reversed string.
    strRev := reverse(str)
    fmt.Println(str)
    fmt.Println(strRev)
}


Output:

Geeks
skeeG

Approach 2: This example declares an empty string and then start appending the characters from the end, one by one.

Example:




// Golang program to reverse a string
package main
  
// importing fmt
import "fmt"
  
// function, which takes a string as
// argument and return the reverse of string.
func reverse(str string) (result string) {
    for _, v := range str {
        result = string(v) + result
    }
    return
}
  
func main() {
  
    // Reversing the string.
    str := "Geeks"
  
    // returns the reversed string.
    strRev := reverse(str)
    fmt.Println(str)
    fmt.Println(strRev)
}


Output:

Geeks
skeeG


Last Updated : 04 May, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads