How to reverse a string by byte or rune

Byte by byte

It’s pretty straightforward to reverse a string one byte at a time.

// Reverse returns a string with the bytes of s in reverse order.
func Reverse(s string) string {
    var b strings.Builder
    for i := len(s) - 1; i >= 0; i-- {
    return b.String()

Rune by rune

To reverse a string by UTF-8 encoded characters is a bit trickier.

// ReverseRune returns a string with the runes of s in reverse order.
// Invalid UTF-8 sequences, if any, will be reversed byte by byte.
func ReverseRune(s string) string {
    res := make([]byte, len(s))
    prevPos, resPos := 0, len(s)
    for pos := range s {
        resPos -= pos - prevPos
        copy(res[resPos:], s[prevPos:pos])
        prevPos = pos
    copy(res[0:], s[prevPos:])
    return string(res)

Example usage

for _, s := range []string{
	"Hello, 世界",
	"\xff\xfe\xfd", // invalid UTF-8
} {
	fmt.Printf("%q\n", ReverseRune(s))
"界世 ,olleH"

Further reading

String functions cheat sheet

Share this page: