Go language Learning (10) bytes packet processing byte slices

Source: Internet
Author: User
Tags anonymous bool comparison lowercase sleep


The bytes package provides a series of functions for reading and writing byte slices
The function of byte slicing is more, it is divided into basic processing function, comparison function, suffix check function, index function, partition function,
Case-handling functions and sub-slice handlers, and so on. 1. Byte slicing basic processing function API 1.1Contains () function


// The function of the Contains () function is to check whether byte slice b contains subslice subslice, return true if it contains, otherwise return false.
func Contains (b, subslice [] bytes) bool
1.2Count () function
The function of the count () function is to calculate the number of bytes slices that Sep displays in a non-overlapping byte slice s.
Func Count (s,sep[]byte) int
1.3Repeat () function
The function of the Repeat () function is to copy the slice B to count and then synthesize a new byte slice back.
Func Repeat (b[]byte,count int) []byte
1.4Replace () function
The function of the/*replace () function is to return a copy of the byte slice s and replace the first n non-overlapping sub-slices old with
new; if n<0, the number of replacements is not limited. The number of times the parameter n is replaced *
/func replace (S,old, new []byte,n int] []byte
1.5Runes () function
The function of the runes () function is to convert s to a UTF-8 encoded byte sequence and return the corresponding Unicode slice.
Func runes (s []byte) []rune
1.6Join () function
The function of the join function is to slice and return each byte slice in s by using the byte slicing Sep to make a single byte slice.
Func Join (s [][]byte,sep[]byte) []byte
[Example]
package main

import (
    "fmt"
    "bytes"
)
func main () {
    // Contains
    b: = [] byte ("mChenys")
    sublice1: = [] byte ("m")
    sublice2: = [] byte ("M")
    fmt.Println (bytes.Contains (b, sublice1)) // true
    fmt.Println (bytes.Contains (b, sublice2)) // false

    // Count
    s: = [] byte ("hahaahaaa")
    sep1: = [] byte ("hah")
    sep2: = [] byte ("aa")
    sep3: = [] byte ("a")
    fmt.Println (bytes.Count (s, sep1)) // 1
    fmt.Println (bytes.Count (s, sep2)) // 2
    fmt.Println (bytes.Count (s, sep3)) // 6

    // Repeat
    b = [] byte ("ha")
    fmt.Println (string (bytes.Repeat (b, 1))) // ha
    fmt.Println (string (bytes.Repeat (b, 2))) // haha

    // Replace
    s = [] byte ("hello, world")
    old: = [] byte ("o")
    news: = [] byte ("ee")
    fmt.Println (string (bytes.Replace (s, old, news, 0))) // hello, world
    fmt.Println (string (bytes.Replace (s, old, news, 1))) // hellee, world
    fmt.Println (string (bytes.Replace (s, old, news, 2))) // hellee, weerld
    fmt.Println (string (bytes.Replace (s, old, news, -1))) / hellee, weerld

    // Runes
    s = [] byte ("Hello world")
    r: = bytes.Runes (s)
    fmt.Println ("The length of the string before conversion:", len (s)) // 12
    fmt.Println ("The length of the converted string:", len (r)) // 4

    // Join
    s: = [] [] byte {[] byte ("Hello"), [] byte ("World")}
    sep1: = [] byte (",")
    fmt.Println (string (bytes.Join (s, sep1))) // Hello, world
    sep2: = [] byte ("#")
    fmt.Println (string (bytes.Join (s, sep2))) // hello # 世界
}
2. Byte Slice comparison function 2.1Compare () function
The function of the/*compare () function is to compare the size of byte slices A and B based on the value of the byte, if a=b, returns 0 if
a>b returns 1 if A<b returns -1.*/
func Compare (a,b[]byte) int
2.2Equal () function
The function of the/*equal () function is used to compare whether 2-byte slices are equal, and if the parameter is nil, it is equivalent to
an empty byte slice, and if a=b, returns True, otherwise false. Case Sensitive *
/func Equal (a,b[]byte ) bool


2.3EqualFold () function


The function of the/*equalfold () function is to convert s and T to UTF-8 strings for comparison,
and ignore case if s=t, return True, otherwise, return false.*/
func equalfold (s,t[]byte) bool
[Example]
Package main

Import (
    "fmt"
    "bytes"
)
func main () {
    //compare
    A: = []byte ("abc")
    B: = []byte ("a")
    FMT. Println (Bytes.compare (b))//1 
    b =[]byte ("ABCD")
    FMT. Println (Bytes.compare (b))//-1
    b =[]byte ("AbC")
    FMT. Println (Bytes.compare (A, b))//1 The  Small letter is greater than the capital letter,
    the =[]byte ("B")
    FMT. Println (Bytes.compare (A, B))//-1 is compared from the first byte if the same again compares the length

    //equal
    a = []byte ("abc")
    B = []byte ("abc")
    FMT. Println (bytes. Equal (A, b))//false
    FMT. Println (bytes. Equal (A,nil))//false
    b = []byte ("abc")
    FMT. Println (bytes. Equal (A, b))//true

    //equalfold
    a = []byte ("abc")
    B = []byte ("abc")
    FMT. Println (bytes. Equalfold (A, b))//true

}
3. Byte-slicing and prefix checking 3.1HasPrefix () function
The function of the Hasprefix () function is to check if the prefix of the byte slice s is prefix, if it is true, if it is not returning false.
Func Hasprefix (s,prefix[]byte) bool
3.2HashSuffix () function
The function of the Hashsuffix () function is to check if the suffix of the byte slice s is suffix, or false if True is returned.
Func Hashsuffix (s,suffix[]byte) bool
[Example]
Package main

Import (
    "fmt"
    "bytes"
)
func main () {
    //hasprefix
    s: = []byte ("Mchenys")
    prefix: = []byte ("M")
    FMT. Println (bytes. Hasprefix (S,prefix))//true
    prefix = []byte ("Men")
    FMT. Println (bytes. Hasprefix (S,prefix))//false

    //hashsuffix
    suffix: = []byte ("Ys")
    FMT. Println (bytes. Hassuffix (S,suffix))//true

}
4. Byte slice position index function


Byte Slice position index function Total 8, index (), Indexany (), Indexbyte (), Indexfunc (), Indexrune (),
LastIndex (), Lastindexany () and Lastindexfunc (). 4.1index () function


Returns the position index of the first occurrence of Sep in S (starting at 0) and returns -1 if Sep is not in S.
Func Index (s,sep []byte) int
4.2IndexAny () function
/* Parses the s into a UTF-8 encoded byte sequence, returns the index position of the first occurrence of any character in the chars in S, and
returns -1.*/
func indexany (s []byte, if it does not contain any one of the characters in chars). chars string) int
4.3IndexByte () function
The function is to check the position index where byte C first appears in S, or -1 if s does not contain C.
Func indexbyte (s[]byte,c byte) int
4.4IndexFunc () function
/* The function is to parse s into a UTF-8 byte sequence and return a position index that satisfies the character C of F (c) =true
, and returns -1.*/
func Indexfunc (s[]byte,f func (R rune) bool if not met) Int
4.5IndexRune () function
/* function is to parse s into a UTF-8 byte sequence and return the position index of the Rune Type R in S,
if s does not contain r then return -1.*/
func indexrune (s[]byte,r rune) int
4.6LastIndex () function
function is to return the position index of the last occurrence of Sep in S, or 1
func LastIndex (s,sep[]byte) int if s does not contain Sep
4.7LastIndexAny () function
/* The function is to parse s into a UTF-8 byte sequence, returning the last position index of any character in the chars in S,
and returning -1*/
func lastindexany if chars is empty or s does not contain any characters from chars. S[]byte,chars string) int
4.8LastIndexFunc () function
/* function is to parse s into a UTF-8 byte sequence, return the position index of the character C that satisfies F (s) =true in S
, and return -1.*/func lastindexfunc if not found
(s[]byte,f func (r Rune) bool) int
[Example]
package main

import (
    "fmt"
    "bytes"
)
func main () {
    // Index
    a: = [] byte ("aaaaa")
    fmt.Println (bytes.Index (a, [] byte ("a"))) // 0
    fmt.Println (bytes.Index (a, [] byte ("aa"))) // 0
    fmt.Println (bytes.Index (a, [] byte ("b"))) //-1

    // IndexAny
    fmt.Println (bytes.IndexAny (a, "a")) // 0
    fmt.Println (bytes.IndexAny (a, "aa")) // 0

    // IndexByte
    s: = [] byte ("google")
    var ch byte = 'g'
    fmt.Println (bytes.IndexByte (s, ch)) // 0

    // IndexFunc, can receive anonymous functions
    fmt.Println (bytes.IndexFunc (s, func (a rune) bool {
        if a == 'o' {
            return true
        } else {
            return false
        }
    }))//1

    // IndexRune
    fmt.Println (bytes.IndexRune (s, 'e')) // 5
    fmt.Println (bytes.IndexRune (s, 'a')) //-1

    // LastIndex
    fmt.Println (bytes.LastIndex (s, [] byte ("g"))) // 3
    fmt.Println (bytes.LastIndex (s, [] byte ("e"))) // 5
    fmt.Println (bytes.LastIndex (s, [] byte ("o"))) // 2

    // LastIndexAny
    fmt.Println (bytes.LastIndexAny (s, "gle")) // 5
    fmt.Println (bytes.LastIndexAny (s, "l")) // 4
    fmt.Println (bytes.LastIndexAny (s, "ge")) // 5

    // LastIndexFunc
    fmt.Println (bytes.LastIndexFunc (s, func (r rune) bool {
        if r == 'g' {
            return true
        } else {
            return false
        }
    })) // 3
}
5. Byte Slice Split function


There are 6 byte slice split functions, fields (), Fieldsfunc (), Split (), SPLITN (),
Splitafter () and Splitaftern () 5.1Fields () functions


/* function is to divide the byte slice s into multiple byte slices according to one or more consecutive whitespace characters, and
if s contains only white space characters, the empty byte slice is returned, where the parameter s prepares the segmented byte slice. *
/func fields (s[]byte) [][]byte Wq
5.2FieldsFunc () function
/* function is to parse s into a UTF-8 byte sequence, for each Unicode character C, if F (c)
returns True, C is split for S as a split character. Returns an empty slice if all characters satisfy F (c) is true. */
Func Fieldsfunc (S []byte,f func (R rune) bool) [][]byte
5.3Split () function
/* function is to divide s into multiple byte slices with sep and return, if Sep is empty, split splits s into
each byte slice corresponding to a UTF-8 character, and split () is equivalent to the SPLITN () function with parameter n. */
func Split (s , sep[]byte) [][]byte
5.4SplitAfter () function
/* Function uses sep as a suffix to slice s into multiple bytes and return. If Sep is empty, the
s tangent is divided into slices of each byte corresponding to a UTF-8 character *
/func Splitafter (s,sep[]byte) [][]byte
5.5SplitAfterN () function
/* function is to use Sep as a suffix to cut s into multiple byte slices and return. If Sep is empty, the s tangent is divided into each byte slice
corresponding to a UTF-8 character. Parameter n determines the length of the returned slice: if n>0, returns a maximum of n sub-byte slices, the
sub-slice may contain an open byte sequence, or, if n=0, returns an empty slice if n< 0 returns all child slices. *
/func splitaftern (s,sep[]byte,n int) [][]byte
5.6SplitN () function
/* function is to divide s with Sep into multiple byte slices and return, if Sep is empty, split the S
cut into each byte slice corresponding to a UTF-8 character, the parameter n determines the return length, n>0 most return that sub-slice;
N==0 Nothing returns, N<0 returns empty slices. *
/func splitn (s,sep []byte,n int) [][]byte
[Example]
package main

import (
    "fmt"
    "bytes"
)
func main () {
    // Fields, which returns a 2-dimensional slice
    s: = [] byte ("a b c")
    for _, v: = range bytes.Fields (s) {
        // Iterate to obtain a 1-dimensional slice, and then force it to a string
        fmt.Print (string (v) + ",") // a, b, c,
    }

    // FieldsFunc, the return is a 2-dimensional slice, receiving anonymous functions
    for _, v: = range bytes.FieldsFunc (s, func (r rune) bool {
        if r == '' {
            return true // Separated by whitespace characters
        } else {
            return false
        }
    }) {
        fmt.Print (string (v) + ",") // a, b, c,
    }

    // Split
    s = [] byte ("eating and sleeping")
    for _, v: = range bytes.Split (s, [] byte ("and")) {
        fmt.Print (string (v) + ",") // eat, sleep,
    }
    for _, v: = range bytes.Split (s, nil) {
        fmt.Print (string (v) + ",") // eat, meal, and, sleep, sleep,
    }

    // SplitAfter
    s = [] byte ("abbcbbd")
    for _, v: = range bytes.SplitAfter (s, [] byte ("bb")) {
        fmt.Print (string (v) + ",") // abb, cbb, d,
    }
    for _, v: = range bytes.SplitAfter (s, nil) {
        fmt.Print (string (v) + ",") // a, b, b, c, b, b, d,
    }

    // SplitAfterN
    s = [] byte ("hehehe")
    for _, v: = range bytes.SplitAfterN (s, [] byte ("he"), 0) {
        fmt.Print (string (v) + ",") // Nothing is output
    }
    for _, v: = range bytes.SplitAfterN (s, [] byte ("he"), 1) {
        fmt.Print (string (v) + ",") // hehehe,
    }
    for _, v: = range bytes.SplitAfterN (s, [] byte ("he"),-1) {
        fmt.Print (string (v) + ",") // he, he, he ,,
    }

    // SplitN
    s = [] byte ("hahaha")
    for _, v: = range bytes.SplitN (s, [] byte ("ha"), 0) {
        fmt.Print (string (v) + ",") // Nothing is output
    }
    for _, v: = range bytes.SplitN (s, [] byte ("ha"), 1) {
        fmt.Print (string (v) + ",") // hahaha,
    }
    for _, v: = range bytes.SplitN (s, [] byte ("ha"),-1) {
        fmt.Print (string (v) + ",") // ,,,,
    }
} 
6. Byte-slice-case processing


A total of 7 functions, Title (), Totitle (), totitlespecial (), ToLower (), tolowerspecial (), ToUpper ()
and Toupperspecial (). 6.1Title () function


function is to return a copy of S, changing the first letter of each word in S to uppercase in Unicode characters.
Func Title (s[]byte) []byte
6.2ToTitle () function
function is to return a copy of S and convert all Unicode characters to uppercase.
Func Totitle (s []byte) []byte
6.3ToTitleSpecial () function
/* function is to return a copy of S and turn all Unicode characters
into uppercase according to the rules specified by _case. *
/func totitlespecial (_case Unicode. specialcase,s []byte] []byte
6.4ToLower () function
function is to return a copy of S and convert all Unicode characters to lowercase.
Func ToLower (s []byte) []byte
6.5ToLowerSpecial () function
/* function is to return a copy of S and convert all Unicode characters to lowercase according to
the rules specified by _case. */
6.6ToUpper () function
is to return a copy of S and capitalize all of the Unicode characters.
6.7ToUpperSpecial () function
/* The function is to return a copy of S and turn all Unicode characters
into uppercase according to the rules specified by _case. *
/func toupperspecial (_case Unicode. Specialcase, S []byte] []byte
Package main

Import (
    "fmt"
    "bytes" "
    Unicode"
)
func main () {
    s: = []byte ("abc")
    FMT . Println (String (bytes. Title (s))//abc
    FMT. Println (String (bytes. Totitle (s)))//abc
    FMT. Println (String (bytes. Totitlespecial (Unicode. azericase,s))//abc
    s = []byte ("ABC")
    FMT. Println (String (bytes. ToLower (s)))//abc
    FMT. Println (String (bytes. Tolowerspecial (Unicode. azericase,s))//abc
    s = []byte ("abc")
    FMT. Println (String (bytes. ToUpper (s)))//abc
    FMT. Println (String (bytes. Toupperspecial (Unicode. azericase,s)))//abc

}
7. Sub-byte slice processing function


A total of 9, Trim (), Trimfunc (), Trimleft (), Trimleftfunc (), TrimRight (), Trimrightfunc (),
Trimspace (), Trimprefix () and Trimsuffix (). 7.1Trim () function


/* function is to return the sub-byte slice of s, and any successive characters appearing at the first and the trailing of s in Cutset
will be deleted. */<
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.