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:
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 := "Geeks"
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:
package main
import "fmt"
func reverse(str string) (result string) {
for _, v := range str {
result = string(v) + result
}
return
}
func main() {
str := "Geeks"
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