Menu Close

Go – Program to reverse a string in go golang

Go does not have built-in function to reverse a string. To reverse a string, we have to write custom function. So, here we are going to write a program to reverse a string in go golang.

Algorithm:

  • Swap characters from begin to end
  • In each iteration, increment begin by 1 and decrement end by 1

Example:

str = "abcd"

begin will be at 'a'
end will be at 'd'


In 1st iteration, str will be:
str = "dbca"

In 2nd iteration, str will be:
str = "dcba"

Here, We are covering two ways to reverse a string in go golang.

  • By using rune
  • By using range

By using rune

package main

import (
  "fmt"
 )

func main(){

  var str = string("abcde")

  chars := []rune(str)

  length := len(str)

  for i := 0; i <  length / 2; i++ {

    ch := chars[i]

    chars[i] = chars[length - i- 1]

    chars[length - i- 1] = ch

  }

  fmt.Printf("%v", string(chars))

}

Output:

edcba

By using range

package main

import (
	"fmt"
)

func main() {

  var str = string("abcd")

  var result string

  for _, v := range str {

    result = string(v) + result

  }
  
  fmt.Print(result)
	
}

Output:

dcba

To learn more about golang, Please refer given below link.

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang

Leave a Reply

Your email address will not be published.

Contact Us