Ejercicios de Go

Reverse a String in Go

Reverse characters and words correctly, including letters like é.

  • Principiante
  • 3 min de lectura
  • 1 ejemplo ejecutable
Lo que aprenderás
  • []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.

Puntos clave

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

Ejemplo ejecutable de Go

Go
Ejecutar 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"))
}
Obtén un botón Run para este ejemplo Resultado de ejecutar el código
oG
olléh
reliable fast simple

Practica

Abre el ejemplo en el compilador online, cambia un valor o añade una línea y predice la salida antes de ejecutarlo. Después rompe el código a propósito y lee el mensaje del compilador.

¿Terminaste esta lección?

Márcala como aprendida para seguir tu progreso.

Siguiente: Arrays →

Practica con un reto

Usa lo que cubre esta lección para resolver un problema real. Cada reto se ejecuta en el navegador, con pruebas al instante y una revisión de IA.

Todos los retos