Menu Close

Go – Get index of the first instance of substring in string

Here, we are going to learn how to get index of the first instance of substring in string by using Index() function of strings package in go golang.

Function Prototype:

func Index(str, substr string) int

Return Value:

Index() function of strings package returns the index of the first instance of substring in string or -1 if substring is not present in string.

Example with code:

package main

import (
  "fmt"
  "strings"
)

func main() {

  var index int

  index = strings.Index("Gabrie", "br")

  fmt.Println(index)


  index = strings.Index("Gabrie", "bob")

  fmt.Println(index)

}

Output:

2
-1

To learn more about golang, Please refer given below link.

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, packages, strings

Leave a Reply

Your email address will not be published. Required fields are marked *