×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang bytes.TrimLeftFunc() Function with Examples

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

bytes.TrimLeftFunc()

The TrimLeftFunc() function is an inbuilt function of the bytes package which is used to get a subslice of the byte slice (s – treated as UTF-8-encoded bytes) by slicing off all leading 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 UTF-8-encoded code points c that satisfy f(c).

Syntax

func TrimLeftFunc(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 bytes.

Return Value

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

Example 1

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

package main

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

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

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

Output:

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

Example 2

// Golang program to demonstrate the
// example of bytes.TrimLeftFunc() 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.TrimLeftFunc(
		[]byte("abcd123abcd"), f1))

	fmt.Printf("%q\n", bytes.TrimLeftFunc(
		[]byte("123abcd456"), f2))

	fmt.Printf("%q\n", bytes.TrimLeftFunc(
		[]byte("abc123@IncludeHelp#456xyz"), f3))
}

Output:

"123abcd"
"abcd456"
"@IncludeHelp#456xyz"

Golang bytes Package »




Comments and Discussions!

Load comments ↻





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