AppDividend
Latest Code Tutorials

Golang String Index() | How To Find Index Of SubString In Go

0

Golang String Index() is an inbuilt function that returns the index of the first instance of substr in s, or -1 if substr is not present in the string. The Index() function is used to find the index value of the first instance of the given string from the original string. If the given string is not available in the original string, then this method will return -1.

Golang String Index()

To find the index of a particular substring of string In Go, you have to import strings package in your program for accessing the Index() function. The function is defined under the strings package so, and You can find the first index value of the specified string from the original string using the Index() function.

Syntax

func Index(s, substr string) int

Parameters

The Index() function takes two parameters. 1) String 2) Substring.

Here, s is the original string, and substr is a string whose we want to find index value.

Return Value

The function returns an index of the substring.

Example

See the following code.

// hello.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Index("Rajesh", "Raj"))
	fmt.Println(strings.Index("Sheldon", "Shely"))
}

Output

go run hello.go
0
-1

The string index is starting from 0.

The Raj is the substring of Rajesh, and the first instance of the Raj substring is 0. So, it will return 0.

In the case of Sheldon, there is no substring Shely, and that is why it returns -1.

Check If Index() function is Case-sensitive

Let’s check if the Index() function is case-sensitive or not.

// hello.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Index("AppDividend", "Dividend"))
	fmt.Println(strings.Index("IMDb", "DB"))
}

Output

go run hello.go
3
-1

It turns out, the Index() function is case sensitive because, in the case of IMDb, the Db and DB are substrings is different, and that is why it can not find it and returns -1.

In the case of AppDividend, the Dividend substring occurs at index 3, that is why it returns 3.

Finally, Golang String Index() example is over.

See also

Golang String Fields()

How To Sort Slice In Golang

How to compare two slices in Golang

Golang String Contains()

Golang String Join()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.