Index()

Published Jul 6, 2023
Contribute to Docs

The Index() function returns the index value of the first occurrence of a substring in the original string, otherwise it returns -1 if the substring is not present in the original string.

Syntax

strings.Index(str, sub_str)

Where str is the original string and sub_str is the substring to find the first occurrence in the original string.

Example

The following example demonstrates the use of the strings.Index() function:

package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Index("chandler","and"))
fmt.Println(strings.Index("navy","as"))
}

The output will be:

2
-1

All contributors

Looking to contribute?

Learn Go on Codecademy