golang

Golang Reverse String

In Go, a string is a sequence of UTF-8 bytes. According to the UTF-8 encoding standard, ASCII characters are single-byte. However, other characters range between 1 and 4 bytes. Because of this inconsistency, it is nearly impossible to index a specific character inside a string.

If we want to index a character in Go, we can convert a string to an array or rune. A rune is basically a Unicode point. A Unicode point refers to a numerical value representing a Unicode character.

This brief article will learn how to reverse a string in Go by first converting it into an array of runes.

Reverse String – Rune by Rune

Consider the example program below:

package main
import (
    "fmt"
)
func main() {
    str := "Hello"
    rune_arr := []rune(str)
    var rev []rune
    for i := len(rune_arr) - 1; i >= 0; i-- {
        rev = append(rev, rune_arr[i])
    }
    fmt.Println("Reverse: ", string(rev))
}

In the example above, we start by converting the string “str” to an array of rune. Doing so allows us to index individual characters in the string.

Once we have the index of individual characters, we append each character to a new string starting from the end to start.

The resulting output is the string in reverse order, as:

Reverse:  olleH

Reverse String – Byte

As mentioned, a string is a sequence of bytes. Hence, we can create the reverse of a string by reversing each byte at a time.

Take the example below:

func reverse(s string) string {
    var byte strings.Builder
    byte.Grow(len(s))
    for i := len(s) - 1; i >= 0; i-- {
        byte.WriteByte(s[i])
    }
    return byte.String()
}

The above example converts a string by reversing it byte by byte.

Conclusion

This article shows you how to reverse a string in the go programming language.

Keep practicing!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list