What is the IndexRune() function in golang?

Overview

The IndexRune() function is used to find the index of the first appearance of Unicode code character in a string.

We import the strings package in the file. We access the IndexRune() function with dot (.) notation (string.IndexRune()).

Syntax

func IndexRune(str string, r rune) int

Parameters

This function takes two arguments:

  • str: This argument is of type string. It represents the list of characters you want to search.

  • r: This represents the rune value of the Unicode character you want to find in the str.

Return value

int: The returned value is the index of the first instance of a Unicode character. It matches the rune value r. If there is no such character in the whole string, then -1 is returned.

Example

package main
import (
"fmt"
"strings"
)
func main() {
str := "This is a greek letter α is used often in mathematics"
x := strings.IndexRune(str, 108)
// 108 is the rune value of l
fmt.Println(" The letter \"l\" first appears at position: ", x)
}

Explanation

We use the IndexRune() function to find the position of the letter ‘l’. The rune value of 108 represents that.

Example

package main
import (
"fmt"
"strings"
)
func main() {
str := "Educative Inc."
x:= strings.IndexRune(str, 108)
// 108 is the rune value of l
if x == -1{
fmt.Print("could not find any \"l\" in : \"",str, "\"" )
}
}

Free Resources