The Index() Function is used to find a substring from the String. It gives us the position of the substring.
package main import "fmt" import "strings" func main() { x := "Hello Beautiful World" y := strings.Index(x, "Beautiful") fmt.Println("The substring is located at the position ",y) }
In the above code, we have declared a String 'Hello Beautiful World' and assigned it to a variable 'x'.
And we would be searching the substring 'Beautiful', from the String, 'Hello Beautiful World'.
So, we have used the 'Index()' Function to find the substring 'Beautiful'.
And what 'Index()' Function does is, goes to the String 'Hello Beautiful World' and searches for the position of the substring 'Beautiful'.
And finds the substring 'Beautiful' in the 6th position. And the position (i.e. '6') is stored in variable 'y'.
And thus prints the position.
Now, let us say you have the below String,
"The Beautiful world is Beautiful indeed"
And you have to search for the substring 'Care'.
Off course the substring 'Care' is not present in the String, "The Beautiful world is Beautiful indeed".
package main import "fmt" import "strings" func main() { x := "The Beautiful world is Beautiful indeed" y := strings.Index(x, "Care") fmt.Println("The substring is located at the position ",y) }
So, if you see the above output, it says '-1'.
Little Weird! Right?
Well! '-1' is returned because the substring 'Care' is not present in the String, "The Beautiful world is Beautiful indeed".
Just remember, if a substring is not found, '-1' is returned.