Start learning free

LESSON 63 OF 671 · STRINGS I

String Find in Go

Lesson

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.

STEP 1 OF 1
    Ctrl + Enter to check