Go Practice Exercises

Reverse a String in Go

Reverse characters and words correctly, including letters like é.

  • Beginner
  • 3 min read
  • 1 runnable example
What you'll learn
  • []rune
  • Swapping with two indexes
  • slices.Reverse
reverse("Go")
  1. 1[]runeG o
  2. 2swapo G
  3. 3string(runes)"oG"

Reverse runes, not bytes

Go strings are UTF-8, so one character can take more than one byte. Reversing a slice of runes keeps letters such as é intact.

[]rune(text) splits the text into characters. Two indexes walk towards each other and swap the characters they point at. strings.Fields splits a sentence into words and slices.Reverse turns their order around.

Key points

  1. A character can take more than one byte.
  2. []rune splits text into characters.
  3. Two indexes swap from both ends.

Runnable Go example

Go
Run code →
main.go
package main

import (
	"fmt"
	"slices"
	"strings"
)

func reverse(text string) string {
	runes := []rune(text)
	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 reverseWords(text string) string {
	words := strings.Fields(text)
	slices.Reverse(words)
	return strings.Join(words, " ")
}

func main() {
	fmt.Println(reverse("Go"))
	fmt.Println(reverse("héllo"))
	fmt.Println(reverseWords("simple fast reliable"))
}
Get a Run button for this example Result of running the code
oG
olléh
reliable fast simple

Practice

Open the example in the online compiler, change a value or add a line, and predict the output before you run it. Then break the code on purpose and read the compiler's message.

Finished this lesson?

Mark it as learned to track your progress.

Next: Arrays →

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges