What is the Index() function in Go?

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

Index() method

It provides the Index() method, which returns the index of the first occurrence of the input substring in the input string.

Syntax

func Index(s, substr string) int

Arguments

This method takes a string s and another string substr to search as inputs.

Return value

  • This method returns the index of the first occurrence of the substring substr in the input string s.

  • It returns -1 if substr does not exist in s.

Getting the index of a substring in a string using Index() method

Code

First, we imported the fmt and strings package to our program in the code below:

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

Explanation

  • After importing fmt, we call the Index() method with "educative.io" as the input string and "io" as the substring to search and get the index. This returns 10, as "io" is present at index 10 in the input string "eductive.io".

  • We again call the Index() method with "educative.io" as the input string and "shots" as the substring to search and get the index. This returns -1, as "shots" is not present in the input string "eductive.io".

  • We show the output of all these operations using the Println() method of the fmt package.

Output

The program shows the below output and exits:

String :  educative.io
substring : io, Index :  10
substring : shots, Index :  -1

Free Resources