bytes.Equal, bytes.Compare, bytes.Contains, bytes.Index, bytes.Join, bytes.Split, bytes.Replace, bytes.TrimSpace
func Equal(a, b []byte) bool
func Compare(a, b []byte) int
func Contains(b, subslice []byte) bool
func Index(s, sep []byte) int
func Join(s [][]byte, sep []byte) []byte
func Split(s, sep []byte) [][]byte
func Replace(s, old, new []byte, n int) []byte
func TrimSpace(s []byte) []byteCompare or search byte slices, join them, split them, replace a limited number of matches, or trim Unicode white space.
| Parameter | Description |
|---|---|
a, b, s | Byte slices to compare, search, join, split, or trim. For Equal and Compare, a nil slice is equivalent to an empty slice. |
sep, old, new, subslice | A separator, a subslice to find, or the old and new sequences for Replace. |
n | For Replace, the maximum number of replacements. If n < 0, there is no limit. |
Returns: Equal and Contains return a boolean. Compare returns -1, 0, or 1. Index returns a byte index or -1. Join, Split, Replace, and TrimSpace return byte slices.
- Replace returns a copy of s. TrimSpace returns a subslice of s, so later writes to the result can change the original slice.
- Split with an empty separator splits after each UTF-8 sequence. To cut around only the first separator, use Cut.
package main
import (
"bytes"
"fmt"
)
func main() {
fmt.Println(bytes.Equal([]byte("ab"), []byte("ab")), bytes.Compare([]byte("a"), []byte("b")))
fmt.Println(bytes.Contains([]byte("hello"), []byte("ell")), bytes.Index([]byte("hello"), []byte("l")))
fmt.Printf("%s\n", bytes.Join([][]byte{[]byte("a"), []byte("b")}, []byte(",")))
fmt.Printf("%q\n", bytes.Split([]byte("a,b,c"), []byte(",")))
fmt.Printf("%s\n", bytes.Replace([]byte("aa"), []byte("a"), []byte("b"), 1))
fmt.Printf("%q\n", bytes.TrimSpace([]byte(" x\n")))
}Expected output
true -1
true 2
a,b
["a" "b" "c"]
ba
"x"