Golang bytes.LastIndex() Function with Examples

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

bytes.LastIndex()

The LastIndex() function is an inbuilt function of the bytes package which is used to get the index of the last instance of a byte subslice (sep) in the byte slice (s).

It accepts two parameters (s, sep []byte) and returns a new byte slice.

Syntax:

func LastIndex(s [][]byte, sep []byte) []byte

Parameter(s):

  • s : The slice of byte slices whose elements are to be concatenated with the sep.
  • sep : The byte slice which is used to be placed as a separator between the elements of s.

Return Value:

The return type of the bytes.LastIndex() function is []byte, it returns a new concatenated byte slice.

Example 1:

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

package main

import (
	"bytes"
	"fmt"
)

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

	fmt.Println(bytes.LastIndex(
		[]byte(str), []byte("Hello")))
	fmt.Println(bytes.LastIndex(
		[]byte(str), []byte("l")))
	fmt.Println(bytes.LastIndex(
		[]byte(str), []byte("Hi")))
}

Output:

0
10
-1

Example 2:

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

package main

import (
	"bytes"
	"fmt"
)

func main() {
	var str string
	var sep string

	str = "Hi! there!"
	sep = "!"

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

	str = "Aspire to inspire before we expire."
	sep = "expire."

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

	str = "Aspire to inspire before we expire."
	sep = "the"

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

Output:

"!" found at the last index 9 in "Hi! there!"
"expire." found at the last index 28 in "Aspire to inspire before we expire."
"the" 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.