Упражнения по Go
Reverse a String in Go
Reverse characters and words correctly, including letters like é.
Что вы узнаете
- []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.
Главное
- A character can take more than one byte.
- []rune splits text into characters.
- Two indexes swap from both ends.
Пример на 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 simpleПрактика
Откройте пример в онлайн-компиляторе, измените значение или добавьте строку и попробуйте предсказать вывод до запуска. Затем намеренно сломайте код и прочитайте сообщение компилятора.
Закончили этот урок?
Отметьте его как изученный, чтобы следить за прогрессом.
Ваш прогресс сохранён в этом браузере Войдите, чтобы он был доступен на всех устройствах.
Попрактикуйтесь на задаче
Примените материал этого урока к реальной задаче. Каждая задача запускается в браузере, с мгновенными тестами и разбором от ИИ.
Все задачи