Menu Close

Go – bytes.TrimLeft() function in go

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

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

bytes.TrimLeft() function prototype:

func TrimLeft(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 of s by slicing off all leading 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\n\n"

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 "$" at left the side
    s := []byte("$$$$$TechieIndoor$$$")
    
    fmt.Printf("%q", bytes.TrimLeft(s, "$"))
    
    
    // trim "\n" at left the side
    s = []byte("\n\nHello World\n\n")
    
    fmt.Printf("\n%q", bytes.TrimLeft(s, "\n"))
    
    
    // trim "&" at left the side
    s = []byte("&&TechieIndoor&&")
    
    fmt.Printf("\n%q", bytes.TrimLeft(s, ""))
    
    
    // trim "&" at left the side
    s = []byte("TechieIndoor&&")
    
    fmt.Printf("\n%q", bytes.TrimLeft(s, "&"))
    
    
    // trim "&" at left the side
    s = []byte("&&TechieIndoor")
    
    fmt.Printf("\n%q", bytes.TrimLeft(s, "&"))
    
}

Output:

"TechieIndoor$$$"
"Hello World\n\n"
"&&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