Golang bytes.IndexRune() Function with Examples

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

bytes.IndexRune()

The IndexRune() function is an inbuilt function of the bytes package which is used to get the byte index of the first occurrence in the byte slice s (interpreted as a sequence of UTF-8-encoded code points) of the given rune.

It accepts two parameters (s []byte, r rune) and returns the byte index of the first occurrence in s of the given rune r. The IndexRune() function may also return -1 if r is not present in s. If r is utf8.RuneError, returns the first instance of any invalid UTF-8 byte sequence.

Syntax:

func IndexRune(s []byte, r rune) int

Parameter(s):

  • s : The byte slice in which we have to check the index of the given rune value.
  • r : The rune value to be checked within the byte slice s.

Return Value:

The return type of the bytes.IndexRune() function is an int, it returns the byte index of the first occurrence in s of the given rune.

Example 1:

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

package main

import (
	"bytes"
	"fmt"
)

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

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

Output:

0
2
1
-1
-1

Example 2:

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

package main

import (
	"bytes"
	"fmt"
)

func main() {
	var str string
	var c rune

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

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

Output:

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