In Go, you can find the index of a substring using strings.Index():
strings.Index(s, sub) // returns index of first occurrence, or -1 if not found
strings.LastIndex(s, sub) // returns index of last occurrence
strings.Index(s[start:], sub) // search only s[start:]; the result counts from `start`
Here are some examples:
sentence := "Hello World"
idx := strings.Index(sentence, "World")
fmt.Println(idx) // 6
if strings.Index(sentence, "xyz") == -1 {
fmt.Println("not found")
}
The index returned is the position of the first character of the found substring. Returns -1 if not found.
Assignment
Follow the Coding Tutorial and find the index of "World" in sentence!
Hint
Use strings.Index(sentence, "World") and assign the result to idx.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
