Menu Close

Go – bytes.TrimSpace() function in go

bytes.TrimSpace() function is used to trim leading and trailing spaces in slice of bytes in go.

TrimSpace() built-in function of bytes package returns a subslice by slicing off all leading and trailing white space in slice of bytes.

bytes.TrimSpace() function prototype:

func TrimSpace(s []byte) []byte

Input parameters:
s: slice of bytes

Return:
It returns a subslice of s by slicing off all leading and trailing white space, as defined by Unicode.

Explanation:

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

Output: "TechieIndoor"

2)
s := []byte("\n\n\tHello World\n\n\t")

Output: "Hello World"

3)
s := []byte{  10, 20   }

Output: {10, 20}

Example:

Code 1:

package main

import (
	"bytes"
	"fmt"
)

// main function
func main() {
    
    s := []byte("   TechieIndoor  ")
    
    fmt.Printf("%q", bytes.TrimSpace(s))
    
    
    s = []byte("\n\n\tHello World\n\n\t")
    
    fmt.Printf("\n%q", bytes.TrimSpace(s))
    
}

Output:

"TechieIndoor"
"Hello World"

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 *