Golang bytes.LastIndexFunc() Function with Examples

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

bytes.LastIndexFunc()

The LastIndexFunc() function is an inbuilt function of the bytes package which is used to get the byte index in the byte slice (s – interpreted as a sequence of UTF-8-encoded code points) of the last Unicode code point satisfying f(c).

It accepts two parameters (s []byte, f func(r rune) bool) and returns the byte index in s of the last Unicode code point satisfying f(c), or -1 if none do.

Syntax:

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

Parameter(s):

  • s : The byte slice in which we have to find the last instance of a byte satisfying the condition.
  • f : The bool function is used to check each byte within the byte slice (s).

Return Value:

The return type of the bytes.LastIndexFunc() function is an int, it returns the byte index in s of the last Unicode code point satisfying f(c), or -1 if none do.

Example 1:

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

package main

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

func main() {
	f := func(c rune) bool {
		return !unicode.IsLetter(c)
	}

	// Returns the last index of first non-letter
	fmt.Printf("%d\n", bytes.LastIndexFunc(
		[]byte("C211, RWA Flats, Delhi65"), f))

	// Returns the last index of first non-letter
	fmt.Printf("%d\n", bytes.LastIndexFunc(
		[]byte("Okay@123!Hello..."), f))
}

Output:

23
16

Example 2:

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

package main

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

func main() {
	f1 := func(c rune) bool {
		return !unicode.IsLetter(c)
	}

	f2 := func(c rune) bool {
		return !unicode.IsNumber(c)
	}

	f3 := func(c rune) bool {
		return !unicode.IsLetter(c) && !unicode.IsNumber(c)
	}

	// Returns the last index of first non-letter byte
	fmt.Printf("%d\n", bytes.LastIndexFunc(
		[]byte("C211, RWA Flats, Delhi65"), f1))

	// Returns the last index of first non-number byte
	fmt.Printf("%d\n", bytes.LastIndexFunc(
		[]byte("Okay@123!Hello..."), f2))

	// Returns the last index of first non-number &
	// non-letter byte
	fmt.Printf("%d\n", bytes.LastIndexFunc(
		[]byte("Okay@123!Hello..."), f3))

	// Returns the last index of first non-number &
	// non-letter byte
	// It will return -1 because there are all letters
	fmt.Printf("%d\n", bytes.LastIndexFunc(
		[]byte("Hello"), f3))
}

Output:

23
16
16
-1

Golang bytes Package »




Comments and Discussions!

Load comments ↻





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