Menu Close

Go – bytes.Trim() function in go

Here, bytes.Trim() function is used to trim leading and trailing bytes in slice with given string in go.

Trim() built-in function of bytes package returns a subslice by slicing off all leading and trailing UTF-8-encoded code points contained in cutset string.

bytes.Trim() function prototype:

func Trim(s []byte, cutset string) []byte

Input parameters:
s: slice of bytes
cutset: String to be sliced off from slice of bytes.

Return:
It returns a subslice by slicing off all leading and trailing UTF-8-encoded code points contained in cutset string.

Explanation:

1)
s := []byte("$$$$$TechieIndoor$$$", "$")

Output: "TechieIndoor"

2)
s := []byte("\n\nHello World\n\n", "\n")

Output: "Hello World"

3)
s := []byte("&&TechieIndoor&&", "")

Output: "&&TechieIndoor&&"

4)
s := []byte("TechieIndoor&&", "&")

Output: "TechieIndoor"

5)
s := []byte("&&TechieIndoor", "&")

Output: "TechieIndoor"

Example:

Code 1:

package main

import (
	"bytes"
	"fmt"
)

// main function
func main() {
    
    // trim "$" both the side, leading and trailing
    s := []byte("$$$$$TechieIndoor$$$")
    
    fmt.Printf("%q", bytes.Trim(s, "$"))
    
    
    // trim "\n" both the side, leading and trailing
    s = []byte("\n\nHello World\n\n")
    
    fmt.Printf("\n%q", bytes.Trim(s, "\n"))
    
    
    // Don't trim both the side, leading and trailing
    s = []byte("&&TechieIndoor&&")
    
    fmt.Printf("\n%q", bytes.Trim(s, ""))
    
    
    // trim "&" both the side, leading and trailing
    s = []byte("TechieIndoor&&")
    
    fmt.Printf("\n%q", bytes.Trim(s, "&"))
    
    
    // trim "&" both the side, leading and trailing
    s = []byte("&&TechieIndoor")
    
    fmt.Printf("\n%q", bytes.Trim(s, "&"))
    
}

Output:

"TechieIndoor"
"Hello World"
"&&TechieIndoor&&"
"TechieIndoor"
"TechieIndoor"

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.

Contact Us