GoLang之buffer与bytes包

strings包

strings包的使用举例:

package main
import s "strings"
import "fmt"

var p = fmt.Println

func main() {
    p("Contains:  ", s.Contains("test", "es"))
    p("Count:     ", s.Count("test", "t"))
    p("HasPrefix: ", s.HasPrefix("test", "te"))
    p("HasSuffix: ", s.HasSuffix("test", "st"))
    p("Index:     ", s.Index("test", "e"))
    p("Join:      ", s.Join([]string{"a", "b"}, "-"))
    p("Repeat:    ", s.Repeat("a", 5))
    p("Replace:   ", s.Replace("foo", "o", "0", -1))
    p("Replace:   ", s.Replace("foo", "o", "0", 1))
    p("Split:     ", s.Split("a-b-c-d-e", "-"))
    p("ToLower:   ", s.ToLower("TEST"))
    p("ToUpper:   ", s.ToUpper("test"))
    p()
    p("Len: ", len("hello"))
    p("Char:", "hello"[1])
}

bytes包

1、大小写转换

func ToUpper(s []byte) []byte { return Map(unicode.ToUpper, s) }
func ToLower(s []byte) []byte { return Map(unicode.ToLower, s) }
func ToTitle(s []byte) []byte { return Map(unicode.ToTitle, s) }

2、比较

func Compare(a, b []byte) int
func Equal(a, b []byte) bool
func EqualFold(s, t []byte) bool

3、替换

// 将 s 中前 n 个 old 替换为 new,n < 0 则替换全部。
func Replace(s, old, new []byte, n int) []byte

// 将 s 中的字符替换为 mapping(r) 的返回值,
// 如果 mapping 返回负值,则丢弃该字符。
func Map(mapping func(r rune) rune, s []byte) []byte

// 将 s 转换为 []rune 类型返回
func Runes(s []byte) []rune

4、清除

// 去掉 s 两边(左边、右边)包含在 cutset 中的字符(返回 s 的切片)
func Trim(s []byte, cutset string) []byte
func TrimLeft(s []byte, cutset string) []byte
func TrimRight(s []byte, cutset string) []byte

// 去掉 s 两边(左边、右边)符合 f 要求的字符(返回 s 的切片)
func TrimFunc(s []byte, f func(r rune) bool) []byte
func TrimLeftFunc(s []byte, f func(r rune) bool) []byte
func TrimRightFunc(s []byte, f func(r rune) bool) []byte

// 去掉 s 两边的空白(unicode.IsSpace)(返回 s 的切片)
func TrimSpace(s []byte) []byte

// 去掉 s 的前缀 prefix(后缀 suffix)(返回 s 的切片)
func TrimPrefix(s, prefix []byte) []byte
func TrimSuffix(s, suffix []byte) []byte

5、分割、连接

// Split 以 sep 为分隔符将 s 切分成多个子串,结果不包含分隔符。
// 如果 sep 为空,则将 s 切分成 Unicode 字符列表。
// SplitN 可以指定切分次数 n,超出 n 的部分将不进行切分。
func Split(s, sep []byte) [][]byte
func SplitN(s, sep []byte, n int) [][]byte

// 功能同 Split,只不过结果包含分隔符(在各个子串尾部)。
func SplitAfter(s, sep []byte) [][]byte
func SplitAfterN(s, sep []byte, n int) [][]byte

// 以连续空白为分隔符将 s 切分成多个子串,结果不包含分隔符。
func Fields(s []byte) [][]byte

// 以符合 f 的字符为分隔符将 s 切分成多个子串,结果不包含分隔符。
func FieldsFunc(s []byte, f func(rune) bool) [][]byte

// 以 sep 为连接符,将子串列表 s 连接成一个字节串。
func Join(s [][]byte, sep []byte) []byte

// 将子串 b 重复 count 次后返回。
func Repeat(b []byte, count int) []byte

6、子串

// 判断 s 是否有前缀 prefix(后缀 suffix)
func HasPrefix(s, prefix []byte) bool
func HasSuffix(s, suffix []byte) bool

// 判断 b 中是否包含子串 subslice(字符 r)
func Contains(b, subslice []byte) bool
func ContainsRune(b []byte, r rune) bool

// 判断 b 中是否包含 chars 中的任何一个字符
func ContainsAny(b []byte, chars string) bool

// 查找子串 sep(字节 c、字符 r)在 s 中第一次出现的位置,找不到则返回 -1。
func Index(s, sep []byte) int
func IndexByte(s []byte, c byte) int
func IndexRune(s []byte, r rune) int

// 查找 chars 中的任何一个字符在 s 中第一次出现的位置,找不到则返回 -1。
func IndexAny(s []byte, chars string) int

// 查找符合 f 的字符在 s 中第一次出现的位置,找不到则返回 -1。
func IndexFunc(s []byte, f func(r rune) bool) int

// 功能同上,只不过查找最后一次出现的位置。
func LastIndex(s, sep []byte) int
func LastIndexByte(s []byte, c byte) int
func LastIndexAny(s []byte, chars string) int
func LastIndexFunc(s []byte, f func(r rune) bool) int

// 获取 sep 在 s 中出现的次数(sep 不能重叠)。
func Count(s, sep []byte) int

buffer包

bytes.buffer是一个缓冲byte类型的缓冲器,这个缓冲器里存放着都是byte。

Buffer结构体定义如下:

type Buffer struct {
    buf       []byte   // contents are the bytes buf[off : len(buf)]
    off       int      // read at &buf[off], write at &buf[len(buf)]
    bootstrap [64]byte // memory to hold first slice; helps small buffers avoid allocation.
    lastRead  readOp   // last read operation, so that Unread* can work correctly.
}

buffer上的操作:

1、初始化buffer

func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }
func NewBufferString(s string) *Buffer { return &Buffer{buf: []byte(s)} }
  • NewBuffer方法将 buf 包装成 bytes.Buffer 对象;
  • NewBufferString方法将string转换为byte之后,包装成bytes.Buffer对象;

2、读buffer

func (b *Buffer) Read(p []byte) (n int, err error)
func (b *Buffer) ReadByte() (c byte, err error)
func (b *Buffer) ReadRune() (r rune, size int, err error)
func (b *Buffer) ReadBytes(delim byte) (line []byte, err error)
func (b *Buffer) ReadString(delim byte) (line string, err error)
func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error)
func (b *Buffer) Next(n int) []byte
  • Read方法将缓存器buf[b.off:]的内容读到参数p中,缓冲器相应的减少了,返回的n为成功读的数量;
  • ReadByte方法返回一个字节;
  • ReadRune方法定义了如何读取Buffer中UTF8编码的rune数据;
  • ReadBytes和ReadString方法读取Buffer中从off到第一次delim之间的数据,并且包括delim;
  • Next方法读取前 n 字节的数据并以切片形式返回,如果数据长度小于 n,则全部读取。

3、写buffer

func (b *Buffer) Write(p []byte) (n int, err error)
func (b *Buffer) WriteString(s string) (n int, err error)
func (b *Buffer) WriteByte(c byte) error
func (b *Buffer) WriteRune(r rune) (n int, err error)
func (b *Buffer) WriteTo(w io.Writer) (n int64, err error)
  • 使用Write方法,将一个byte类型的slice放到缓冲器的尾部;
  • 使用WriteString方法,将一个字符串放到缓冲器的尾部;
  • 使用WriteByte方法,将一个byte类型的数据放到缓冲器的尾部;
  • 使用WriteRune方法,将一个rune类型的数据放到缓冲器的尾部;
  • 使用WriteTo方法,将一个缓冲器的数据写到w里,w是实现io.Writer的,比如os.File就是实现io.Writer;
时间: 2024-08-29 05:16:17

GoLang之buffer与bytes包的相关文章

go语言中bytes包的常用函数,Reader和Buffer的使用

bytes中常用函数的使用: package main; import ( "bytes" "fmt" "unicode" ) //bytes包中实现了大量对[]byte操作的函数和两个最主要的Reader和Buffer两个结构 func main() { str := "aBcD"; //转为小写 fmt.Println(string(bytes.ToLower([]byte(str)))); //转为大写 fmt.Prin

用Golang自己构造ICMP数据包

ICMP是用来对网络状况进行反馈的协议,可以用来侦测网络状态或检测网路错误. 限于当前Golang在网络编程方面的代码稀缺,资料甚少,所以分享一个用Golang来构造ICMP数据包并发送ping程序的echo消息的实例. RFC792定义的echo数据包结构: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Go语言学习(十)bytes包处理字节切片

bytes包提供了对字节切片进行读写操作的一系列函数 字节切片处理的函数比較多,分为基本处理函数,比較函数,后缀检查函数,索引函数,切割函数, 大写和小写处理函数和子切片处理函数等. 1.字节切片基本处理函数api 1.1Contains()函数 //Contains()函数的功能是检查字节切片b是否包括子切片subslice,假设包括返回true,否则返回false. func Contains(b,subslice []bytes) bool 1.2Count()函数 //Count()函数

golang bytes包解读

golang中的bytes标准库实现了对字节数组的各种操作,与strings标准库功能基本类似. 功能列表:1.字节切片 处理函数 (1).基本处理函数(2).字节切片比较函数(3).前后缀检查函数(4).字节切片位置索引函数(5).分割函数(6).大小写处理函数(7).子字节切片处理函数2.Buffer 对象3.Reader 对象 基本处理函数Contains() :返回是否包含子切片func Contains(b, subslice []byte) bool 案例:执行结果:[email p

golang bytes 包 详解

概况: 包字节实现了操作字节切片的函数.它类似于琴弦包的设施. 函数: func Compare(a, b []byte) int func Contains(b, subslice []byte) bool func ContainsAny(b []byte, chars string) bool func ContainsRune(b []byte, r rune) bool func Count(s, sep []byte) int func Equal(a, b []byte) bool

golang中tcp socket粘包问题和处理

转自:http://www.01happy.com/golang-tcp-socket-adhere/ 在用golang开发人工客服系统的时候碰到了粘包问题,那么什么是粘包呢?例如我们和客户端约定数据交互格式是一个json格式的字符串: {"Id":1,"Name":"golang","Message":"message"} 当客户端发送数据给服务端的时候,如果服务端没有及时接收,客户端又发送了一条数据上来

sync:与golang的并发息息相关的包

楔子 我们知道golang除了兼顾了开发速度和运行效率之外,最大的亮点就是在语言层面原生支持并发,也就是通过所谓的goroutine.不过既然是并发,那么就势必会面临很多问题.比如:资源竞争,多个goroutine同时访问一个资源会发生竞争从而产生意想不到的结果,那么这时候我们会通过加锁来解决:主goroutine不能先退出,这时候我们会等待子goroutine.还有单例模式,以及对象池等等.那么golang是如何实现的呢?就是通过下面我们要介绍的sync包. sync.Mutex sync.M

Golang自带的http包的路由规则问题

1.调用下面的方法开启一个http监听服务http.HandleFunc("/hello/", helloHandler)err := http.ListenAndServe(":8080", nil)if err= nil { log.Fatal("ListenAndServe: ", err.Error())}2.路由规则中新增了"/hello"和"/hello/"两个key对应的handler(hel

go bytes包

代码: package main import ("bytes""fmt"// "icode.baidu.com/baidu/gdp/automaxprocs"// "icode.baidu.com/baidu/gdp/log") // "icode.baidu.com/baidu/gdp/log" // "icode.baidu.com/baidu/gdp/log" func main