How to Reverse a String in Golang?

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
}

chevron_right


Output:

Geeks
skeeG

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

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
}

chevron_right


Output:

Geeks
skeeG



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.