Published on

How to reverse a string, number, array and slice in Go?

How to reverse a string, number, array and slice in Go?

How to reverse in Go

How to reverse a string in Go?

   package main

   import "fmt"

   func ReverseString(s string) string {
      r := []rune(s)
      for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
         r[i], r[j] = r[j], r[i]
      }

      return string(r)
   }

   func main(){
      fmt.Println(ReverseString("Bangalore"))
      fmt.Println(ReverseString("Golang"))
      fmt.Println(ReverseString("javascript"))
   }

   // output
   // erolagnaB
   // gnaloG
   // tpircsavaj

How to Reverse a number in Go?

   package main
   import "fmt"
   func ReverseNumber(num int) int {

      res := 0
      for num>0 {
         remainder := num % 10
         res = (res * 10) + remainder
         num /= 10
      }
      return res
   }

   func main(){
      fmt.Println(ReverseNumber(234))
      fmt.Println(reverseNumber(567))
   }

   //output

   //432
   //765

How to Reverse a array in Go?

   package main
   import "fmt"

   func reverseArray(arr []int) []int{
      for i, j := 0, len(arr)-1; i<j; i, j = i+1, j-1 {
         arr[i], arr[j] = arr[j], arr[i]
      }
      return arr
   }

   func main(){
      fmt.Println(reverseArray([]int{1, 2, 3, 4, 5}))
      //output = [5 4 3 2 1]
   }

How to Reverse a slice in Go?

Reverse a slice using string values in below example -


   package main
   import "fmt"
   func main() {

      var slice []string
      slice = append(slice, "Delhi") // create slice using append function
      slice = append(slice, "Mumbai")
      slice = append(slice, "Bangalore")
      slice = append(slice, "Jaipur")

      fmt.Println("The slice before reversal is:", slice)
      for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
         slice[i], slice[j] = slice[j], slice[i]   // reverse the slice
      }

      fmt.Println("The slice after reversal is:")
      fmt.Println(slice)  // print the reversed slice

   }