×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang bytes.TrimFunc() Function with Examples

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

bytes.TrimFunc()

The TrimFunc() 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 c that satisfy f(c).

It accepts two parameters (s []byte, f func(r rune) bool) and returns a subslice of s by slicing off all leading and trailing UTF-8-encoded code points c that satisfy f(c).

Syntax

func TrimFunc(s []byte, f func(r rune) bool) []byte

Parameters

  • s : The byte slice for trimming.
  • f : The bool function to check and remove the leading and trailing bytes.

Return Value

The return type of the TrimFunc() function is a []byte, it returns a subslice of s by slicing off all leading and trailing UTF-8-encoded code points c that satisfies f(c).

Example 1

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

package main

import (
	"bytes"
	"fmt"
	"unicode"
)

func main() {
	// Returns true if character is either letter or number
	// Thus, the bytes.TrimFunc() function will remove all
	// leading and trailing letters or numbers
	f := func(c rune) bool {
		return unicode.IsLetter(c) || unicode.IsNumber(c)
	}

	fmt.Printf("%q\n", bytes.TrimFunc(
		[]byte("C211, RWA Flats, Delhi65"), f))
	fmt.Printf("%q\n", bytes.TrimFunc(
		[]byte("Okay@123!Hello..."), f))
}

Output:

", RWA Flats, "
"@123!Hello..."

Example 2

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

package main

import (
	"bytes"
	"fmt"
	"unicode"
)

func main() {
	// Returns true if character is letter
	f1 := func(c rune) bool {
		return unicode.IsLetter(c)
	}

	// Returns true if character is number
	f2 := func(c rune) bool {
		return unicode.IsNumber(c)
	}
	// Returns true if character is either letter or number
	f3 := func(c rune) bool {
		return unicode.IsLetter(c) || unicode.IsNumber(c)
	}

	fmt.Printf("%q\n", bytes.TrimFunc(
		[]byte("abcd123abcd"), f1))
		
	fmt.Printf("%q\n", bytes.TrimFunc(
		[]byte("123abcd456"), f2))
		
	fmt.Printf("%q\n", bytes.TrimFunc(
		[]byte("abc123@IncludeHelp#456xyz"), f3))
}

Output:

"123"
"abcd"
"@IncludeHelp#"

Golang bytes Package »




Comments and Discussions!

Load comments ↻





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