Bài tập Go

Reverse a String in Go

Reverse characters and words correctly, including letters like é.

  • Cơ bản
  • Đọc trong 3 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • []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.

Những điểm quan trọng

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

Ví dụ Go chạy được

Go
Chạy 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"))
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
oG
olléh
reliable fast simple

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Tiếp theo: Arrays →

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách