Open In App
Related Articles

How to Reverse a String in Golang?

Improve Article
Improve
Save Article
Save
Like Article
Like

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

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 04 May, 2020
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials