OneBite.Dev - Coding blog in a bite size

reverse a string in Go

Code snippet on how to reverse a string in Go

  package main
  import "fmt"

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

func main() {
  fmt.Println(Reverse("hello world"))
}

This code was written in Go and is used to reverse a string. First, we import the fmt library, which provides us with printf-style formatting. Then, a function is declared called “Reverse,” which takes a string as a parameter. Within this function, the string is converted to a “rune,” which is like a character type for strings in Go. A for loop is then used to iterate through the rune from the beginning to the end. Here, the first and last runes are swapped, and the loop then continues to the second and second-to-last runes, and so on. The reversed rune is then converted back to a string and returned. Finally, the Reverse function is called in the main function with the string “hello world” as a parameter, and it is printed to screen.

go