Golang bytes.IndexRune() function example

package bytes

IndexRune interprets the given input as a sequence of UTF-8-encoded Unicode code points. It returns the byte index of the first occurrence in the given input of the given rune and it returns -1 if rune has no match

 package main

 import (
 "bytes"
 "fmt"
 )

 func main() {
 slice := []byte("abcdefg")
 slicebyteindex := bytes.IndexRune(slice, 'd')

 fmt.Printf("d index num is %d inside the string %s\n", slicebyteindex, string(slice))

 utf8slice := []byte("大世界和小世界")

 utf8byteindex := bytes.IndexRune(utf8slice, '小')
 fmt.Printf("小 index num is %d inside the string %s\n",  utf8byteindex, string(utf8slice))


 utf8byteindex2 := bytes.IndexRune(utf8slice, '界')
 fmt.Printf("界 index num is %d inside the string %s\n",  utf8byteindex2, string(utf8slice))

 }

Output :

d index num is 3 inside the string abcdefg

小 index num is 12 inside the string 大世界和小世界

界 index num is 6 inside the string 大世界和小世界

Reference :

http://golang.org/pkg/bytes/#IndexRune

Advertisement