strings.Index() Function in Golang With Examples

strings.Index() Function in Golang is used to get the first instance of a specified substring. If the substring is not found, then this method will return -1.

Syntax:

func Index(str, sbstr string) int

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

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Go program to illustrate the 
// String Index() Function
  
package main 
     
import ( 
    "fmt"
    "strings"
     
// Main function 
func main() { 
     
    // Creating and initializing the strings 
    str1 := "Welcome to GeeksforGeeks"
    str2 := "My name is XYZ"
     
    // Displaying strings 
    fmt.Println("String 1: ", str1) 
    fmt.Println("String 2: ", str2) 
     
    // Using Index() function 
    res1 := strings.Index(str1, "Geeks"
    res2 := strings.Index(str2, "is"
   
    // Displaying the result 
    fmt.Println("\nIndex values:"
    fmt.Println("Result 1: ", res1) 
    fmt.Println("Result 2: ", res2) 
     

chevron_right


Output:

String 1:  Welcome to GeeksforGeeks
String 2:  My name is XYZ

Index values:
Result 1:  11
Result 2:  8

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Go program to illustrate the
// String Index() Function
  
package main
  
import (
    "fmt"
    "strings"
)
  
// Main function
func main() {
  
    // Using Index() function
    res1 := strings.Index("GFG", "H")
    res2 := strings.Index("GeeksforGeeks", "for")
  
    // Displaying the result
    fmt.Println("Result 1: ", res1)
    fmt.Println("Result 2: ", res2)
  
}

chevron_right


Output:

Result 1:  -1
Result 2:  5



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.