How to find the Index of a string in Golang?


Strings.Index is a built-in function in Golang that returns the index of the first instance of a substring in a given string. If the substring is not available in the given string, then it returns -1.

Syntax

The syntax of Index() is as follows −

func Index(s, substring string) int

Where,

  • s – Original given string
  • substring – It is the string whose Index value we need to find

Example 1

Let us consider the following example −

package main
import (
   "fmt"
   "strings"
)
// Main function
func main() {
   
   // Initializing the Strings
   x := "Learn Golang on Tutorialspoint"

   // Display the Strings
   fmt.Println("Given String:", x)

   // Using the Index Function
   result1 := strings.Index(x, "Golang")
   result2 := strings.Index(x, "TUTORIALSPOINT")

   // Display the Index Output
   fmt.Println("Index of 'Golang' in the Given String:", result1)
   fmt.Println("Index 'TUTORIALSPOINT' in the Given String:", result2)
}

Output

It will produce the following output −

Given String: Learn Golang on Tutorialspoint
Index of 'Golang' in the Given String: 6
Index 'TUTORIALSPOINT' in the Given String: -1

Notice that the Index() function is case-sensitive. That is why, it returns the index of TUTORIALSPOINT as -1.

Example 2

Let us take another example.

package main
import (
   "fmt"
   "strings"
)
func main() {
   
   // Initializing the Strings
   p := "Index String Function"
   q := "String Package"

   // Display the Strings
   fmt.Println("First String:", p)
   fmt.Println("Second String:", q)

   // Using the Index Function
   output1 := strings.Index(p, "Function")
   output2 := strings.Index(q, "Package")

   // Display the Index Output
   fmt.Println("Index of 'Function' in the 1st String:", output1)
   fmt.Println("Index of 'Package' in the 2nd String:", output2)
}

Output

It will generate the following output −

First String: Index String Function
Second String: String Package
Index of 'Function' in the 1st String: 13
Index of 'Package' in the 2nd String: 7

Updated on: 10-Mar-2022

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements