bytes包
bytes.Buffer
bytes.Buffer
是一个用于缓冲字节的缓冲区,提供了高效的读写操作。
package main
import (
"bytes"
"fmt"
)
func main() {
var buffer bytes.Buffer
buffer.WriteString("Hello, ")
buffer.WriteString("World!")
fmt.Println(buffer.String()) // 输出: Hello, World!
}
package main
import (
"bytes"
"fmt"
)
func main() {
a := []byte("Hello, World!")
b := []byte("World")
// 比较
fmt.Println(bytes.Compare(a, b)) // 输出: 1
// 包含
fmt.Println(bytes.Contains(a, b)) // 输出: true
// 相等
fmt.Println(bytes.Equal(a, b)) // 输出: false
// 查找
fmt.Println(bytes.Index(a, b)) // 输出: 7
// 连接
s := [][]byte{[]byte("Hello"), []byte("World")}
fmt.Println(string(bytes.Join(s, []byte(", ")))) // 输出: Hello, World
// 分割
fmt.Println(bytes.Split([]byte("a,b,c"), []byte(","))) // 输出: [[97] [98] [99]]
// 修剪
fmt.Println(string(bytes.Trim([]byte(" Hello, World! "), " "))) // 输出: Hello, World!
}