How to Find the Index of a String in Golang

To find the index of a string in a Go, you can use the “Strings.Index()” method. The Strings.Index() is a built-in Go function that returns the index of the first instance of a substring in a given string. If the substring is unavailable in the given string, it returns -1.

Syntax

func Index(str, substring string) int

Parameters

  1. str: It is an initially provided string
  2. substring – It is the string whose Index value we need to find

Example 1

package main

import (
  "fmt"
  "strings"
)

// Main function
func main() {

  // Initializing the Strings
  text := "Go is an open-source programming language created at Google."

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

  // Using the Index Function
  result1 := strings.Index(text, "open-source")
  result2 := strings.Index(text, "Python")

  // Display the Index Output
  fmt.Println("Index of 'open-source' in the Given String:", result1)
  fmt.Println("Index of 'Python' in the Given String:", result2)

  // Using the Count Function
  count1 := strings.Count(text, "o")
  count2 := strings.Count(text, "Go")

  // Display the Count Output
  fmt.Println("Number of 'o' occurrences in the Given String:", count1)
  fmt.Println("Number of 'Go' occurrences in the Given String:", count2)
}

Output

Given String: Go is an open-source programming language created at Google.
Index of 'open-source' in the Given String: 9
Index of 'Python' in the Given String: -1
Number of 'o' occurrences in the Given String: 6
Number of 'Go' occurrences in the Given String: 2

In this code example, we use the strings.Index() function to find the index of the first occurrence of the specified substrings within the given string. If the substring is not found, the function returns -1.

We also used the strings.Count() function to count the occurrences of the specified substrings within the given string.

Example 2

package main

import (
  "fmt"
  "strings"
)

func main() {

  // Initializing the Strings
  s1 := "Go is a powerful language"
  s2 := "Golang is fun"

  // Display the Strings
  fmt.Println("First String:", s1)
  fmt.Println("Second String:", s2)

  // Using the Index Function
  output1 := strings.Index(s1, "powerful")
  output2 := strings.Index(s2, "fun")

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

Output

First String: Go is a powerful language
Second String: Golang is fun
Index of 'powerful' in the 1st String: 8
Index of 'fun' in the 2nd String: 10

In this example, we used the “strings.Index()” function to find the index of the first occurrence of the specified substrings within the given strings. If the substring is not found, the function returns -1.

Leave a Comment