Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
communitycreator

How to reverse a string in Golang

Shubham Singh Kshatriya

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 main

import "fmt"

// function to reverse string
func reverseString(str string) (result string) {
	// iterate over str and prepend to result
	for _ , v := range str {
		result = string(v) + result
	}
	return
}

func main() {
	str := "Educative-Edpresso"

	fmt.Println(str)
	// invoke reverseString
	fmt.Println(reverseString(str))
}
Reversing a string in Go

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 returns result.

  • Line 15: We declare a string str inside the main() function.

  • Line 17: We output str on the console.

  • Line 19: We invoke the reverseString function, pass str as an argument, and output the result on the console.

RELATED TAGS

golang
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring