Go – Get Index of Substring in String

To get the index of a substring in a string in Go programming, call Index function of strings package, and pass the string and substring as arguments to this function.

The syntax to get the index of the first occurrence of substring substr in a string str using strings.Index() is

</>
Copy
 strings.Index(str, substr)

where

  • strings is the package.
  • Index is the function name.
  • str is the string in which we have to find the index of substr.

strings.Index() function returns an integer that represents the position of first occurrence of substr in str.

Examples

In the following program, we will take a string Welcome to Go Tutorial, Go Examples and find the index of first occurrence of substring Go.

example.go

</>
Copy
package main

import (
	"fmt"
	"strings"
)

func main() {
	var str = "Welcome to Go Tutorial, Go Examples"
	var substr = "Go"
	var index = strings.Index(str, substr)
	fmt.Println("The index of substring in this string is: ", index)
}

Output

The index of substring in this string is:  11

If the substring is not present in the input string, strings.Index() returns -1.

In the following program, we will take a string and substring such that substring is not present in the string. We will then use Index() to find the index of substring in given string. Since substring is not present in the string, Index() should return -1.

example.go

</>
Copy
package main

import (
	"fmt"
	"strings"
)

func main() {
	var str = "Welcome to Go Tutorial, Go Examples"
	var substr = "Python"
	var index = strings.Index(str, substr)
	fmt.Println("The index of substring in this string is: ", index)
}

Output

The index of substring in this string is:  -1

Conclusion

In this Golang Tutorial, we learned how to find the index of a substring in given string using strings.Index() function.