Golang bytes.LastIndexByte() Function with Examples

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

bytes.LastIndexByte()

The LastIndexByte() function is an inbuilt function of the bytes package which is used to get the index of the last instance of the given byte (c) in the byte slice (s).

It accepts two parameters (s []byte, c byte) and returns the index of the last instance of c in s, or -1 if c is not present in s.

Syntax:

func LastIndexByte(s []byte, c byte) int

Parameter(s):

  • s : The byte slice in which we have to find the last instance of a byte (c).
  • c : The byte value which is to be checked within the byte slice (s).

Return Value:

The return type of the bytes.LastIndexByte() function is an int, it returns the index of the last instance of c in s, or -1 if c is not present in s.

Example 1:

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

package main

import (
	"bytes"
	"fmt"
)

func main() {
	str := "Hello, world!"

	fmt.Println(bytes.LastIndexByte(
		[]byte(str), 'H'))
	fmt.Println(bytes.LastIndexByte(
		[]byte(str), 'l'))
	fmt.Println(bytes.LastIndexByte(
		[]byte(str), 'e'))
	fmt.Println(bytes.LastIndexByte(
		[]byte(str), 'x'))
	fmt.Println(bytes.LastIndexByte(
		[]byte(str), 'y'))
}

Output:

0
10
1
-1
-1

Example 2:

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

package main

import (
	"bytes"
	"fmt"
)

func main() {
	var str string
	var c byte

	str = "Hi there!"
	c = '!'

	result := bytes.LastIndexByte([]byte(str), c)
	if result != -1 {
		fmt.Printf("%c found at the last index %d in %q\n",
			c, result, str)
	} else {
		fmt.Printf("%c doest not found in %q\n",
			c, str)
	}

	str = "Aspire to inspire before we expire."
	c = 't'

	result = bytes.LastIndexByte([]byte(str), c)
	if result != -1 {
		fmt.Printf("%c found at the last index %d in %q\n",
			c, result, str)
	} else {
		fmt.Printf("%c doest not found in %q\n",
			c, str)
	}

	str = "Aspire to inspire before we expire."
	c = 'z'

	result = bytes.LastIndexByte([]byte(str), c)
	if result != -1 {
		fmt.Printf("%c found at the last index %d in %q\n",
			c, result, str)
	} else {
		fmt.Printf("%c doest not found in %q\n",
			c, str)
	}
}

Output:

! found at the last index 8 in "Hi there!"
t found at the last index 7 in "Aspire to inspire before we expire."
z doest not found in "Aspire to inspire before we expire."

Golang bytes Package »





Comments and Discussions!

Load comments ↻






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