Skip to content

Instantly share code, notes, and snippets.

@CypherpunkSamurai
Last active September 30, 2021 09:32
Show Gist options
  • Save CypherpunkSamurai/7866efc2c0b5452334593f0fb5070efd to your computer and use it in GitHub Desktop.
Save CypherpunkSamurai/7866efc2c0b5452334593f0fb5070efd to your computer and use it in GitHub Desktop.
Reversing a String in Golang

Reverse an Array in Golang

This example shows how to reverse an array in golang. You can use this in your stringutils.go file for your projects

In this example we use an array of strings. the array type can be of anything but same type

The source array

const myarray = []string{"hi", "golang", "this", "is", "array"}

Define a (fixed size) array according to the size of the source array

rev := make([]string, len(myarray))

Run a for loop from: 0-length of array -1

int i will +1 every loop

int j will -1 every loop

we take object from: myarray index i

and place at: rev array index j

we take object from: myarray index j

and place at: rev array index i

so, [1,2,3] is placed [3,2,1]

thus filling rev array from start and end. meeting at the center index.

so when i == j we are at center, we need to run until i < j. because i is 0.

run until i <= j, so they meet at the center object completing both sides

for i, j := 0, len(myarray)-1; i <= j; i,j = i+1, j-1 {
    rev[i], rev[j] = myarray[j], myarray[i]
}

fmt.Printf("Original Array: %+v\n", myarray)
fmt.Printf("Reversed Array: %+v\n", rev)
// @author: CypherpunkSamurai
// Language Golang
/*
This example shows how to reverse an array in golang.
You can use this in your stringutils.go file for your projects
In this example we use an array of strings.
the array type can be of anything but same type
*/
// The source array
const myarray = []string{"hi", "golang", "this", "is", "array"}
// Define a (fixed size) array according to the size of the source array
rev := make([]string, len(myarray))
/*
Run a for loop from: 0-length of array -1
int i will +1 every loop
int j will -1 every loop
we take object from: myarray index i
and place at: rev array index j
we take object from: myarray index j
and place at: rev array index i
so,
[1,2,3] is placed
[3,2,1]
thus filling rev array from start and end. meeting at the center index.
so when i == j we are at center, we need to run until i < j. because i is 0.
run until i <= j, so they meet at the center object completing both sides
*/
for i, j := 0, len(myarray)-1; i <= j; i,j = i+1, j-1 {
rev[i], rev[j] = myarray[j], myarray[i]
}
fmt.Printf("Original Array: %+v\n", myarray)
fmt.Printf("Reversed Array: %+v\n", rev)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment