Exercícios de Go
Reverse a String in Go
Reverse characters and words correctly, including letters like é.
O que você vai aprender
- []rune
- Swapping with two indexes
- slices.Reverse
reverse("Go")
- 1
[]runeG o - 2
swapo G - 3
string(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
- A character can take more than one byte.
- []rune splits text into characters.
- Two indexes swap from both ends.
Exemplo executável de Go
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"))
}
oG
olléh
reliable fast simplePratique
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.
Seu progresso está salvo neste navegador Entre para mantê-lo em todos os dispositivos.
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