To find the index of a substring in Go, you can use the strings.Index
function.
In this example,
strings
package.str
with a string value.strings.Index
function to find the index of a specific substring within str
.strings.Index
function returns the starting index of the substring in the string.package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello World"
index := strings.Index(str, "World")
fmt.Println("Index of substring is:", index)
}
Index of substring is: 6
In this example,
strings
package.str1
and str2
with different values.strings.Index
function to find the index of str2
within str1
.strings.Index
function returns the starting index of str2
in str1
.package main
import (
"fmt"
"strings"
)
func main() {
str1 := "apple banana cherry banana"
str2 := "cherry"
index := strings.Index(str1, str2)
fmt.Println("Index of substring is:", index)
}
Index of substring is: 13
In this tutorial, we learned How to find the Index of Substring in Go language with well detailed examples.