Golang bytes.Index() Function with Examples

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

bytes.Index()

The Index() function is an inbuilt function of the bytes package which is used to get the index of the first instance of sep in s, or -1 if sep is not present in s. Where sep and s are byte slices.

It accepts two parameters (s, sep []byte) and returns the first index of sep in s.

Syntax:

func Index(s, sep []byte) int

Parameter(s):

  • s : The byte slice in which we have to check the byte subslice (sep).
  • sep : The byte subslice to be checked in byte slice s.

Return Value:

The return type of the bytes.Index() function is an int, it returns the first index of sep in s.

Example 1:

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

package main

import (
	"bytes"
	"fmt"
)

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

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

Output:

0
2
-1

Example 2:

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

package main

import (
	"bytes"
	"fmt"
)

func main() {
	var str string
	var sep string

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

	result := bytes.Index([]byte(str), []byte(sep))
	if result != -1 {
		fmt.Printf("%q found at the 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.Index([]byte(str), []byte(sep))
	if result != -1 {
		fmt.Printf("%q found at the 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.Index([]byte(str), []byte(sep))
	if result != -1 {
		fmt.Printf("%q found at the index %d in %q\n", sep, result, str)
	} else {
		fmt.Printf("%q doest not found in %q\n", sep, str)
	}
}

Output:

"!" found at the index 8 in "Hi there!"
"expire." found at the 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.