แบบฝึกหัด Go

Reverse a String in Go

Reverse characters and words correctly, including letters like é.

  • ระดับเริ่มต้น
  • อ่าน 3 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • []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.

ประเด็นสำคัญ

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

ตัวอย่าง Go ที่รันได้

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"))
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
oG
olléh
reliable fast simple

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Arrays →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด