×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang bytes.Trim() Function with Examples

Golang | bytes.Trim() Function: Here, we are going to learn about the Trim() function of the bytes package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 28, 2021

bytes.Trim()

The Trim() function is an inbuilt function of the bytes package which is used to get a subslice of the byte slice (s) by slicing off all leading and trailing UTF-8-encoded code points contained in the string (cutset).

It accepts two parameters (s []byte, cutset string) and returns a subslice of s by slicing off all leading and trailing UTF-8-encoded code points contained in the cutset.

Syntax

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

Parameters

  • s : The byte slice for trimming.
  • cutset : The string which contains the characters to be removed.

Return Value

The return type of the Trim() function is a []byte, it returns a subslice of s by slicing off all leading and trailing UTF-8-encoded code points contained in the cutset.

Example 1

// Golang program to demonstrate the
// example of bytes.Trim() function

package main

import (
	"bytes"
	"fmt"
)

func main() {
	fmt.Printf("%s\n", bytes.Trim(
		[]byte("!!!Hello!!! World.!!!"), "!"))
	fmt.Printf("%s\n", bytes.Trim(
		[]byte("   Hello    World.   "), " "))
	fmt.Printf("%s\n", bytes.Trim(
		[]byte("Hi How are you?"), "Hi "))
}

Output:

Hello!!! World.
Hello    World.
ow are you?

Example 2

// Golang program to demonstrate the
// example of bytes.Trim() function

package main

import (
	"bytes"
	"fmt"
)

func main() {
	var str []byte
	var cutset string
	var result []byte

	str = []byte("!!!Hello!!! World.!!!")
	cutset = "!"
	result = bytes.Trim(str, cutset)
	fmt.Printf("Original string: %q\n", str)
	fmt.Printf("Trimmed string: %q\n", result)
	fmt.Println()

	str = []byte("   Hello    World.   ")
	cutset = " "
	result = bytes.Trim(str, cutset)
	fmt.Printf("Original string: %q\n", str)
	fmt.Printf("Trimmed string: %q\n", result)
	fmt.Println()

	str = []byte("Hi How are you?")
	cutset = "Hi "
	result = bytes.Trim(str, cutset)
	fmt.Printf("Original string: %q\n", str)
	fmt.Printf("Trimmed string: %q\n", result)
}

Output:

Original string: "!!!Hello!!! World.!!!"
Trimmed string: "Hello!!! World."

Original string: "   Hello    World.   "
Trimmed string: "Hello    World."

Original string: "Hi How are you?"
Trimmed string: "ow are you?"

Golang bytes Package »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.