What is strings.IndexAny() in Go?

The strings package is a Go standard library package that contains functions to manipulate UTF-8 encoded strings.

The strings package provides the IndexAny() method, which returns the index of the first occurrence of any Unicode code points from the input substring. These are present in the input string.

Syntax

func IndexAny(s, chars string) int

Parameters

This method takes a string s and another string chars as an input.

Return value

  • It returns the first occurrence of the Unicode code points from the input substring chars, which are present in the input string s.

  • It returns -1 if none of the Unicode code points from the chars string are present in s.

Using IndexAny() to find the index of any of the input chars from the string

Code

package main
import (
"fmt"
"strings"
)
func main() {
str1 := "educative.io"
fmt.Println("String : ", str1)
index1 := strings.IndexAny(str1, "ma")
index2 := strings.IndexAny(str1, "xyz")
fmt.Println("substring : ma,", "Index : ", index1)
fmt.Println("substring : xyz,", "Index : ", index2)
}

Free Resources