Exercícios de Go

Reverse a String in Go

Reverse characters and words correctly, including letters like é.

  • Iniciante
  • 3 min de leitura
  • 1 exemplo executável
O que você vai aprender
  • []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.

Pontos-chave

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

Exemplo executável de Go

Go
Executar código →
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"))
}
Gerar um botão Run para este exemplo Resultado da execução
oG
olléh
reliable fast simple

Pratique

Abra o exemplo no compilador online, mude um valor ou adicione uma linha e tente prever a saída antes de executar. Depois quebre o código de propósito e leia a mensagem do compilador.

Terminou esta lição?

Marque como aprendida para acompanhar seu progresso.

Próxima: Arrays →

Pratique com um desafio

Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.

Todos os desafios