How to reverse a string in Golang
In Golang (v1.62.2), there is no built-in method to reverse a string, so we will create our own function to serve this purpose.
Algorithm
Let’s go through the approach to solving this problem first.
- Step 1: Define a function that accepts a string.
- Step 2: Iterate over the input string and prepend the characters one by one to the resultant string.
- Step 3: Return the resultant string.
Code
The code below demonstrates how to reverse a string.
package mainimport "fmt"// function to reverse stringfunc reverseString(str string) (result string) {// iterate over str and prepend to resultfor _ , v := range str {result = string(v) + result}return}func main() {str := "Educative-Edpresso"fmt.Println(str)// invoke reverseStringfmt.Println(reverseString(str))}
Explanation
-
Line 5: We create the
reverseString()function. -
Line 6: The function accepts a string, iterates over it, and prepends each character to
result. At the end of the function, it returnsresult. -
Line 15: We declare a string
strinside themain()function. -
Line 17: We output
stron the console. -
Line 19: We invoke the
reverseStringfunction, passstras an argument, and output the result on the console.