Go: how to reverse a string: two approaches

Reversing a string is a common operation in programming, and the Go programming language offers several ways to do it efficiently and cleanly. In this article, we will explore some of the most common techniques for reversing a string using the Go language.

Method 1: Using Runes and Slicing


package main

import "fmt"

func reverseString(input string) string {
    runes := []runes(input)
    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() {
    str := "Hello, Go!"
    reversed := reverseString(str)
    fmt.Println("Original string:", str)
    fmt.Println("Reversed string:", reversed)
}

In this approach, we convert the string into an array of runes, which represent individual Unicode characters. We then use a for loop to swap the characters from the end to the beginning of the rune array, thus obtaining the reversed string.

Method 2: Using a Buffer


package main

import (
    "fmt"
    "bytes"
)

func reverseStringWithBuffer(input string) string {
    var buffer bytes.Buffer
    for i := len(input) - 1; i >= 0; i-- {
        buffer.WriteByte(input[i])
    }
    return buffer.String()
}

func main() {
    str := "Hello, Go!"
    reversed := reverseStringWithBuffer(str)
    fmt.Println("Original string:", str)
    fmt.Println("Reversed string:", reversed)
}

In this second approach, we use a byte buffer to construct the reversed string. We iterate over the original string starting from the end and add each character to the buffer.

Conclusions

Both of these methods are valid for reversing a string in Go, but choosing between them may depend on the specific needs of your project. Using runes is especially useful when dealing with strings that contain Unicode characters, while the buffer approach can be more efficient in some scenarios.

Back to top