Home »
Golang »
Golang Reference
Golang strings.Index() Function with Examples
Golang | strings.Index() Function: Here, we are going to learn about the Index() function of the strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 16, 2021
strings.Index()
The Index() function is an inbuilt function of strings package which is used to get the index of the first occurrence (instance) of a substring in a string. It accepts two parameters – string and substring and returns the index, or returns -1 if the substring is not present in the string.
Syntax
func Index(str, substr string) int
Parameters
- str : String in which we have to check the substring.
- substr : Substring to be checked in the string.
Return Value
The return type of Index() function is an int, it returns the index of the first occurrence (instance) of a substring in a string, or -1 if the substring is not present in the string.
Example 1
// Golang program to demonstrate the
// example of strings.Index() Function
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Index("Hello, world", "world"))
fmt.Println(strings.Index("abcdabba", "ab"))
fmt.Println(strings.Index("abcdabba", "ce"))
}
Output:
7
0
-1
Example 2
// Golang program to demonstrate the
// example of strings.Index() Function
package main
import (
"fmt"
"strings"
)
func main() {
var str string
var substr string
var index int
str = "Hello, world!"
substr = "world"
index = strings.Index(str, substr)
if index >= 0 {
fmt.Printf("%q found in %q at %d index.\n", substr, str, index)
} else {
fmt.Printf("%q does not found in %q.\n", substr, str)
}
str = "Hello, world!"
substr = "l"
index = strings.Index(str, substr)
if index >= 0 {
fmt.Printf("%q found in %q at %d index.\n", substr, str, index)
} else {
fmt.Printf("%q does not found in %q.\n", substr, str)
}
str = "Hello! Hi! How are you?"
substr = "H"
index = strings.Index(str, substr)
if index >= 0 {
fmt.Printf("%q found in %q at %d index.\n", substr, str, index)
} else {
fmt.Printf("%q does not found in %q.\n", substr, str)
}
str = "Hello! Hi! How are you?"
substr = "am"
index = strings.Index(str, substr)
if index >= 0 {
fmt.Printf("%q found in %q at %d index.\n", substr, str, index)
} else {
fmt.Printf("%q does not found in %q.\n", substr, str)
}
}
Output:
"world" found in "Hello, world!" at 7 index.
"l" found in "Hello, world!" at 2 index.
"H" found in "Hello! Hi! How are you?" at 0 index.
"am" does not found in "Hello! Hi! How are you?".
Golang strings Package Functions »