ข้ามไปที่เนื้อหาหลัก

วิธีต่อสตริง Golang

string concatenation เป็นพื้นฐานที่สุดในการเขียนโปรแกรมหลาย ๆ ภาษาจะใช้เครื่องหมาย + ในภาษา Go ก็เช่นกัน

มาดูกันครับ มีแบบต่างๆให้เราเลือกใช้แบบไหนบ้าง

1.ใช้งาน buffer Package byte

package main

import ( "bytes" "fmt" )
func main() {
var str bytes.Buffer
// เริ่มต้นด้วย "Hello "
str.WriteString("Hello ")
// ต่อคำว่า world! ลงในตัวแปร
str.WriteString("world!")
fmt.Println(str.String())
}

ใช้งานฟังก์ชัน bytes.WriteString ในการต่อสตริง และแปลงให้อยู่ในรูปแบบตัวแปรสตริงด้วยฟังก์ชัน bytes.String
  
2. ใช้งานฟังก์ชัน copy

package main
import "fmt" 
func main() { 
str:= make([]byte, 13) i := 0  
// เริ่มต้นด้วย "Hello " 
i += copy(str[i:], "Hello, ")
// ต่อคำว่า world! ต่อลงไปใน byte
i += copy(str[i:], "world!") 
fmt.Println(string(str)) 
}
ตัวแปร slice ของ byte สามารถ convert type เป็นสตริงได้เลย

3. ใช้งานฟังก์ชัน join
package main
import ( "fmt" "strings" )
func main() {
str := make([]string, 0)
str = append(str, "Hello, ")
// ต่อคำว่า world! ต่อลงไปใน string   
str = append(str, "world!")
fmt.Println(strings.Join(str, ""))
}

ความคิดเห็น