Menu Close

Go – Trim prefix bytes in slice of bytes in go

Here, bytes.TrimPrefix() function is used to trim prefix bytes in slice of bytes in go. It trims leading prefix in slice of bytes.

TrimPrefix() built-in function of bytes package returns slice of bytes without the provided leading prefix string.

bytes.TrimPrefix() function prototype:

func TrimPrefix(s, prefix []byte) []byte

Input parameters:
s: slice of bytes
prefix: Slice of bytes to be trimmed leading prefix in s

Return:
It returns slice of bytes without the provided leading prefix string.

Explanation on trim prefix bytes in slice of bytes in go

1)
s := []byte("foo bar 123 4  baz")
prefix := []bytes("foo")

Output:
" bar 123 4  baz"

2)
s := []byte("foo bar 123 4  baz")
prefix := []bytes("bar")

Output:
"foo bar 123 4  baz"

3)
s := []byte("foo bar 123 4  baz")
prefix := []bytes("")

Output:
"foo bar 123 4  baz"

4)
s := []byte("foo bar 123 4  baz")
prefix := []bytes("John")

Output:
"foo bar 123 4  baz"

Example:

Code 1:

package main

import (
    "fmt"
    "bytes"
)


func main() {
    s := []byte("foo bar 123 4  baz")
    prefix := []byte("foo")
    
    fmt.Printf("%q", bytes.TrimPrefix(s, prefix))
    
    
    s = []byte("foo bar 123 4  baz")
    prefix = []byte("bar")
    
    fmt.Printf("\n%q", bytes.TrimPrefix(s, prefix))
    
    
    s = []byte("foo bar 123 4  baz")
    prefix = []byte("")
    
    fmt.Printf("\n%q", bytes.TrimPrefix(s, prefix))
    
    
    s = []byte("foo bar 123 4  baz")
    prefix = []byte("John")
    
    fmt.Printf("\n%q", bytes.TrimPrefix(s, prefix))
}

Output:

% go run sample.go

" bar 123 4  baz"
"foo bar 123 4  baz"
"foo bar 123 4  baz"
"foo bar 123 4  baz"

To learn more about golang, Please refer given below link:

References:

https://golang.org/doc/

Posted in bytes, golang, packages

Leave a Reply

Your email address will not be published. Required fields are marked *