Menu Close

Go – Get first index of rune in slice of bytes in go

bytes.IndexRune() is used to get first index of rune in slice of bytes in go. It returns the byte index of the first occurrence of the rune.

Function prototype:

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

Input parameters:
s: Slice of bytes
r: rune to be searched in s

Returns:
1: It returns the byte index of the first occurrence in s of the given rune.
2: It returns -1 if rune is not present in s

Explanation on get index of rune in slice of bytes in go:

  • IndexRune() function interprets slice of bytes as a sequence of UTF-8-encoded code points.
  • If rune is utf8.RuneError then It returns the first instance of any invalid UTF-8 byte sequence.

Example:

1)
s := []byte("Techieindoor")
r := 'i'

Output: 4 
rune 'i' is present at 4th and 6th position in slice of bytes i.e "Techieindoor". IndexRune() function returns first occurrence of rune in slice of bytes so here, It's in 4th position.

2)
s := []byte("Techieindoor")
r := 'z'

Output: -1 
rune 'z' is not present in slice of bytes i.e "Techieindoor".

3)
s := []byte("Techieindoor")
r := 'n'

Output: 7

4)
s := []byte{10, 20, 30, 40, 50, 20, 20}
r := '20'

Output: 2

Example with code:

package main

import (
  "fmt"
  "bytes"
)

func main() {

    s := []byte("Techieindoor")
    r := 'i'
    fmt.Printf("Index: %d", bytes.IndexRune(s, r))

  
    s = []byte("Techieindoor")
    r = 'z'
    fmt.Printf("\nIndex: %d", bytes.IndexRune(s, r))


    s = []byte("Techieindoor")
    r = 'n'
    fmt.Printf("\nIndex: %d", bytes.IndexRune(s, r))


}

Output:

% go run sample.go

Index: 4
Index: -1
Index: 7

To learn more about golang, Please refer given below link:

References:

https://golang.org/pkg/

Posted in bytes, golang, packages

Leave a Reply

Your email address will not be published. Required fields are marked *