Write a Golang Program to Reverse a String



Examples

  • Input str = “himalaya” => Reverse String would be like => “ayalamih”
  • Input str = “mountain” => Reverse String would be like => “niatnuom”

Approach to solve this problem

  • Step 1: Define a function that accepts a string, i.e., str.
  • Step 2: Convert str to byte string.
  • Step 3: Start iterating the byte string.
  • Step 4: Swap the first element with the last element of converted byte string.
  • Step 5: Convert the byte string to string and return it.

Program

Live Demo

package main
import "fmt"
func reverseString(str string) string{
   byte_str := []rune(str)
   for i, j := 0, len(byte_str)-1; i < j; i, j = i+1, j-1 {
      byte_str[i], byte_str[j] = byte_str[j], byte_str[i]
   }
   return string(byte_str)
}

func main(){
   fmt.Println(reverseString("himalaya"))
   fmt.Println(reverseString("taj"))
   fmt.Println(reverseString("tropical"))
}

Output

ayalamih
jat
laciport
Updated on: 2021-02-04T11:02:57+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements