Golang--byte slices

Source: Internet
Author: User
Tags uppercase character
This is a creation in Article, where the information may have evolved or changed.

The Go language standard library bytes, which implements various operations on byte arrays. It is analogous to the facilities of strings package. (It is similar to the functionality provided by the string standard package)
The functions provided are as follows;

    • BYTE Slice processing function
      • Basic processing functions
      • BYTE Slice comparison function
      • Pre-and post-prefix check function
      • Byte Slice position index function
      • Split function
      • Case handling functions
      • Sub-byte slice processing function
    • BufferObject
    • ReaderObject

BYTE Slice processing function

Basic processing function Total Seven

    1. Contains () returns whether a child slice is included
    2. Count () sub-tiles number of non-overlapping instances
    3. Map () function, convert byte to Unicode, and then replace
    4. Repeat () copies the slice to count this, returning this new slice
    5. Replace () replaces part of a slice with another part
    6. Runes () converts S to the corresponding UTF-8 encoded byte sequence, and returns the corresponding Unicode slice
    7. Join () function to concatenate sub-byte slices together.

func Contains(b, subslice []byte) bool

func Contains(b, subslice [] byte) boolCheck for Byte slice B, whether to include sub-byte slices subslice

package mainimport (    "bytes"    "fmt")func main() {    // 这里不能写成 b := []byte{"Golang"},这里是利用类型转换。    b := []byte("Golang")    subslice1 := []byte("go")    subslice2 := []byte("Go")    fmt.Println(bytes.Contains(b, subslice1))    fmt.Println(bytes.Contains(b, subslice2))}

Counts(s, spe[ []byte) int

func Count(s, sep []byte) intComputes the number of non-overlapping instances of the sub-byte slice that Sep appears in the byte slice s.

 Package MainImport(    "bytes"    "FMT")func Main(){  s := []byte ("banana") sep1: = []byte ("ban") SEP2: = [] byte ("NA") sep3: = []byte ("a") FMT. Println (bytes.  Count (S, sep1)) FMT. Println (bytes.  Count (S, SEP2)) FMT. Println (bytes.  Count (S, sep3))   }

func Map(mapping func(r rune) rune, s []byte) []byte

Map function: First convert s to UTF-8 encoded character sequence, then use mapping to map each Unicode character to the corresponding character, and finally save the result in a new byte slice.

package mainimport (    "bytes"    "fmt")func main() {    s := []byte("同学们,上午好")    funcrunerune {        if'上' {            '下'        }        return r    }    fmt.Println(string(s))    fmt.Println(string(bytes.Map(m, s)))}

func Repeat(b []byte, count int) []byte

func Replace(s, old, new []byte, n int) []byte

Returns a copy of the byte slice S and replaces the first n non-overlapping sub-slices old with new, if n < 0 does not limit the number of replacements

package  Main import  ( "bytes"   "FMT" ) func  Main () {s: = []byte  (" google "" old: = []byte  ( "O"  ) //here new is a byte slice, not a keyword anymore  new : = []byte  ( "oo" ) N: = 1  F Mt. Println (string  (bytes. Replace (S, old, new , N))) Fmt. Println (string  (bytes. Replace (S, old, new , ))}}  

func Runes(b []byte) []rune

Converts a byte slice to the corresponding UTF-8 encoded byte sequence, and returns the corresponding Unicode slice.

package mainimport (    "bytes"    "fmt")//每个 rune 变量占据 4个字节,等价于 int32//每个 byte 变量占据1个字节,等价于int8func main() {    s := []byte("中华人民共和国")    r := bytes.Runes(s)    fmt.Println(stringlen(s))  //字节切片的长度    fmt.Println(stringlen(r))   // rune 切片的长度}

func Join(s [][]byte, sep []byte) []byte

Slice each byte slice in the Sep bar s in bytes into one and return.

 PackageMainImport("bytes"    "FMT")funcMain () {each element of the//byte slice is still a byte slice. s: = []byte{        []byte("Hello"),        []byte("The World"),//Here's a comma, essential} Sep: = []byte(",") FMT. Println (string(bytes. Join (S, Sep)))varA = []int{1,2,3,5,//Here's a comma, also essential} FMT. Println (a)varb = []int{1,2,3,4,5}//The last element here does not require a commaFmt. Println (b)}

BYTE Slice comparison function

func Compare(a, b[]byte) int: Returns an integer: 1, 0, 1
func Equal(a, b []byte) bool: Returns TRUE or False
func EqualFold(a, b []byte) bool: Ignore case: Returns True or False

package mainimport ( "bytes " " FMT ") Func main () {a : = []byte  ( "abc" ) b: = []byte  (     "ABC" ) s: = []byte  ( "Golang" ) T: = []byte  (" Golang ") fmt. Println (bytes . Compare (a , B)) fmt. Println (bytes . Equal (a , B)) fmt. Println (bytes . Equalfold (S, t))} output is: 1  false  true   

BYTE slice pre-and post-prefix check function

func HasPreifx(s, prefix []byte) bool
func HasSuffix(s, suffix []byte) bool

Byte Slice position index function

    • func Index(s, sep []byte) intReturns the position of the first occurrence of the byte slice in S (the index starts at 0), and no return-1 exists.
    • func IndexAny(s []byte, chars string)Interprets a byte slice as a UTF-8 character, returning the position of the first occurrence of any character in the chars in S. (The Unicode character set is saved in chars)
    • func IndexByte(s []byte, c byte) int
    • func IndexFunc(s []byte, f func(r rune)bool) intThe S is interpreted as a UTF-8 byte sequence, and the first index position of the character C that makes F (c) = Ture is returned.
    • func IndexRue(s []byte, r rune)
    • func LastIndex(s ,sep []byte) int
    • func LastIndexAny (s []byte, chars string) int
    • func LastIndexFunc(s []byte, f func(r rune) bool) int

BYTE Slice Split function

    • func fields (s []byte) [][]byte splits the byte slice s by one or more consecutive whitespace characters into multiple byte slices. If s contains only white space characters, an empty byte slice is returned.
package  Main import  ( "bytes"   "FMT" ) func  Main () {s: = []byte  (" I ' m a student. ) for  _, F: = range  bytes. Fields (s) {fmt. Printf ( "%q" , F)} s1: = []byte  () S2: = bytes. Fields (S1) fmt. Println (len  (s2), S2 = = nil )} program output is as follows:  "I ' m"    "student."   0  false   
  • func FieldsFunc(s []byte, f func(r rune) bool) [][]byte, the S is first interpreted as a sequence of Unicode characters and then tested with function f.
  • func Split(s, sep []byte) [][]byteSegmentation by byte sequence Sep
  • func SplitN(s, sep []byte, n int) [][]byteDivide by the byte sequence Sep, and you can set the number of bytes sliced, n = = 1 to return all sub-slices.
  • func SplitAfter(s, sep[] byte) [][]byte, this is not to abandon Sep, but to retain Sep.
  • func SplitAfterN(s, sep[] byte, int n) [][]byteIt was the same as last time.

    BYTE-slice case-processing function

    • func Title(s []byte) []byteReturns a copy of S and converts the first letter of each word in s to a Unicode uppercase character.
    • func ToTitle(s []byte) []byteConverts all of the Unicode characters into uppercase.
    • func ToTitleSpecial(_case unicode.SpecialCase, s []byte) []byte
    • func ToLower(s []byte) []byte
    • func ToLowerSpeical(_case unicode.SpecialCase, s[]byte) []byte
    • func ToUpper(s []byte) []byte
    • func ToUpperSpecial (_case unicode.SpecialCase, s []byte) []byte

Sub-byte slice processing function

Truncate a byte slice and return the new byte slice

funcTrim (S []byte, Cutsetstring) []bytefuncTrimfunc (S []byteFfunc(rRune)BOOL) []bytefuncTrimleft (S []byte, Cutsetstring) []bytefuncTrimleftfunc (S []byteFfunc(rRune)BOOL) []bytefuncTrimRight (S []byte, Cutsetstring) []bytefuncTrimrightfunc (S []byteFfunc(rRune)BOOL) []bytefuncTrimprefix (s, prefix []byte) []bytefuncTrimsuffix (s, suffix []byte) []bytefuncTrimspace (S []byte) []byte

Buffer and Reader

It is now necessary to read and write byte slices: for example, writing a string to a byte slice, reading a string from a byte slice, and so on.
So we have Buffer and Reader.

bytes. Buffer

Buffer is a type buffer struct{in the bytes package ...}

A buffer is a variable-sized buffer of bytes with Read and Write methods. The zero value for Buffer is a empty Buffer ready-to-use. (is a variable-length buffer with the Read and write methods.) The 0 value of buffer is an empty buffer, but can be used)
In my opinion: Buffer is an abstraction, think of it as an unlimited reservoir, you can add water to it, but also can be taken out of the water. (Deposit data, and fetch data)

    1. Create a Buffer (in fact the bottom is a []byte, byte slice)
    2. Write data to (write Mtheods)
    3. Read data from (Write methods)

Create Buffer

var b bytes.Buffer  //直接定义一个 Buffer 变量,而不用初始化b.Writer([]byte("Hello "// 可以直接使用new(bytes.Buffer)   //直接使用 new 初始化,可以直接使用// 其它两种定义方式func NewBuffer(buf []byte) *Bufferfuncstring) *Buffer

Buffer Basic function

func (b *Buffer) Bytes() []byteReturns content that is not read
func (b *Buffer) Grow() (n int)Increase the capacity of the buffer
func (b *Buffer) Len() intReturns the length of content that is not read
func (b *Buffer) Next(n int) []byteReturns n bytes that are not read, side effects, as if the Read method was used.

reading data to Buffer

func (*Buffer) Read(p []byte) (n int, err error)From buffer, read the data from Len (p) until the buffer has no data to read. The return value is the number of bytes that read the data. If no data can be read, then the value of err is IO. Eof
func (*Buffer) ReadByte() (c byte, err error)
func (*Buffer) ReadBytes(delim byte) (line []byte, err error)When the first Delim is encountered, the data is returned.
func (*Buffer)ReadRune() (r rune, err error)
func (*Buffer) ReadString(delim byte) (line string, err error)
func (*Buffer) Reset()Empty data, no data to read
func (*Buffer) String() stringReturns unread data as a string

func (*Buffer) Truncate(n int)Preserves n unread data in buffer.

func (*Buffer) UnreadByte() error
func (*Buffer) UnreadRune() errorBe careful to return errors.

func (*Buffer) ReadFrom( r o.Reader) (n int64, err error)Reads the data from the IO interface object R and writes to buffer, knowing that R.read returns IO. Eof. Of course

Writing data to Buffer

func (b * Buffer) Write(p []byte) (n int, err error)Writes the byte slice p to buffer.
func (b *Buffer) WriteByte(c byte) error
func (b *Buffer) WriteRune(c byte) error
func (b *Buffer) WriteString(s string) (n int, err error)
func (b *Buffer) WriteTo(w io.Writer) (n int64, err error)Writes the data in buffer to the I/O object writer, knowing that the data is empty or encountering an error.

bytes. Reader

Reader is another way to manipulate slices, but reader can only read the data and not write data from the tiles. Reader supports the positioning of slices Seek() .

Summarize

Explains the following:
1. []byte byte slicing is the (most) important tool in Golang, making good use of byte slices
2. Master the tools for manipulating byte slices. (It is important to have good tools)
3. Write more programs before you can harvest

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.