Reverse Strings Rune By Rune

Reversing bytes scrambles multi-byte runes into invalid UTF-8, so reversal has to walk []rune pairs from both ends to keep text intact.

GoData Integrity

Code

gosnippet
28 lines
package main

import "fmt"

// byte-wise reverse: multi-byte characters get split into invalid UTF-8
func reverseBytes(s string) string {
	out := make([]byte, len(s))
	for i := 0; i < len(s); i++ {
		out[len(s)-1-i] = s[i]
	}
	return string(out)
}

// rune-wise reverse: swap runes pairwise from both ends toward the middle
func reverseRunes(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() {
	text := "héllo"
	fmt.Println("byte reverse:", reverseBytes(text))
	fmt.Println("rune reverse:", reverseRunes(text))
	fmt.Println("rune count:", len([]rune(text)), "byte count:", len(text))
}

Inside the snippet

Reverse Strings Rune By Rune keeps everything in the functions reverseBytes, reverseRunes and main.

for i := 0; i < len(s); i++ is the loop that carries the per-item work.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

Entry signature: func reverseBytes(s string) string

The file’s steps are announced right in the output: byte reverse:, rune reverse:, rune count:.

The entry point wires reverseBytes and reverseRunes together — run it once and the whole demo flows.

The core lines, annotated

func reverseBytes(s string) string {
	out := make([]byte, len(s))
	for i := 0; i < len(s); i++ {
		out[len(s)-1-i] = s[i]
	}
	return string(out)
}
func reverseRunes(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() {
	text := "héllo"
	fmt.Println("byte reverse:", reverseBytes(text))
	fmt.Println("rune reverse:", reverseRunes(text))
	fmt.Println("rune count:", len([]rune(text)), "byte count:", len(text))
}

Interactive Tools for This Topic

FAQ

What does Reverse Strings Rune By Rune print when run?
The script runs standalone; its 3 labeled outputs include `byte reverse:`, `rune reverse:`, `rune count:`.