Home » Golang String Index() Function

Golang String Index() Function

Index() function in the Golang strings package returns the index of the first instance of the substring in the given string. If the given string doesn’t contain a substring, it returns -1.

Index() Syntax

The syntax for Index() function is:

func Index(s1, substr string) int

Index() Parameters

The Index() function takes two string arguments

s1 is the string

substr is the string

Index() Return Value

The strigs package Index() function returns an integer value.It returns the index of the first instance of substr in a given string s1. If the given string doesn’t contain substr, it returns -1.

Let’s understand the string package Index() method with examples.

strings.Index() function to get the index of a substring in a given string

The following go program returns the index of a substring in a given string using the strings.Index() function.

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Index("Refer GolangSpot for Go Articles", "Go"))
	fmt.Println(strings.Index("Refer GolangSpot", "Article"))
}

The output of the above program is:

6
-1

In the above program,

The first output has a -6 value as the substring “Go” is present in the given string “Refer GolangSpot for Go Articles” at index 6.

The second output has a -1 value as the given string “Refer GolangSpot” doesn’t find any appearance of substring “Articles”.

Cool Tip: How to use the string HasSuffix function in Golang!

Conclusion

I hope the above article on the Index() method to return an index of a substring in a given string is helpful to you.

You can find more topics about the Golang tutorials on the GolangSpot Home page.

Leave a Comment