พื้นฐาน Go
Go Strings and the strings Package
Join, search, split, trim and slice text in Go.
สิ่งที่คุณจะได้เรียนรู้
- Building strings
- Contains, Index, Split
- Slicing a string
message[0:5]
H0
e1
l2
l3
o4
,5
Read-only text with many helpers
A Go string is a read-only sequence of bytes, usually UTF-8 text. You cannot change a string in place, but you can build new ones, and the strings package has functions for most everyday jobs.
+= builds a new string. len counts bytes. Contains and Index search the text, Split cuts it at a separator and returns a slice, and message[0:5] takes the bytes from position 0 up to, but not including, 5.
ประเด็นสำคัญ
- A string cannot be changed in place.
- len counts bytes.
message[0:5]takes bytes 0 to 4.
ตัวอย่าง Go ที่รันได้
main.go
package main
import (
"fmt"
"strings"
)
func main() {
message := "Hello, Go"
message += "!"
fmt.Println(message)
fmt.Println(len(message), strings.ToUpper(message))
fmt.Println(strings.Contains(message, "Go"), strings.Index(message, "Go"))
fmt.Println(strings.Split("a,b,c", ","))
fmt.Println(strings.Repeat("=", 5), strings.TrimSpace(" padded "))
fmt.Println(message[0:5], string(message[7]))
}
Hello, Go!
10 HELLO, GO!
true 7
[a b c]
===== padded
Hello Gฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- นับจำนวนสระ นับจำนวนสระในข้อความที่กำหนด ง่าย
- Initials From a Name Build uppercase initials from a full name. ง่าย