Write a Golang program to reverse a string

Go ProgrammingServer Side ProgrammingProgramming

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
raja
Published on 04-Feb-2021 11:01:13
Advertisements