strings.Index() method in Golang

The index () method is used to find the index of the specified string. This post will look at the Index() method of the strings package in detail.

  • Method declaration – func Index(s, substr string) int
  • What does it do? Index() methods find the first occurrence of the string substr in the string s.
    • So, if the substring is present at multiple indexes in the specified string, then only the first occurrence will be fetched and returned.
  • What does it return? Index() method will return an int value representing the index of the first occurrence of the substring. It will return -1 if there is no occurrence of the substring within the specified string.

Remember, the indexing here starts from 0. So, if the first occurrence of the substring starts from the 3rd element, then Index() method will return 2.

package main

import (
	"fmt"
	"strings"
)

func main() {

	index1 := strings.Index("codekru", "kru")               // this will return 4
	index2 := strings.Index("codekru", "Hi")                // this will return -1
	index3 := strings.Index("hello codekru hello", "hello") // this will return 0

	fmt.Println("index of kru in the string is:", index1)
	fmt.Println("index of hi in the string is:", index2)
	fmt.Println("index of hello in the string is:", index3)

}

Output –

index of kru in the string is: 4
index of hi in the string is: -1
index of hello in the string is: 0

The function returned -1 for the string that didn’t exist within the specified string.

The What If scenarios

Q – What if we pass an empty string as the substring?

Here, it will return 0, as illustrated by the below program.

package main

import (
	"fmt"
	"strings"
)

func main() {

	index := strings.Index("codekru", "") // this will return 0

	fmt.Println("index of empty string is:", index)

}

Output –

index of empty string is: 0
Q – What if the substring’s length > string length?

It will compare the length of the first argument with the second. As the second argument’s length is greater than the first, it will return -1.

package main

import (
	"fmt"
	"strings"
)

func main() {

	index := strings.Index("codekru", "codekru hi") // this will return -1

	fmt.Println("index is:", index)

}

Output –

index is: -1

Please visit this link to learn more about the Strings in Go language and its other functions or methods.

We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.

Liked the article? Share this on

Leave a Comment

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