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
substrin the input strings. -
It returns -1 if
substrdoes not exist ins.
Code
First, we imported the fmt and strings package to our program in the code below:
package mainimport ("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 theIndex()method with"educative.io"as the input string and"io"as the substring to search and get the index. This returns10, as"io"is present at index10in 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 thefmtpackage.
Output
The program shows the below output and exits:
String : educative.io
substring : io, Index : 10
substring : shots, Index : -1