How to Find Index of Substring in Go: Simple Guide
In Go, you can find the index of a substring using the
strings.Index function from the strings package. It returns the position of the first occurrence of the substring or -1 if the substring is not found.Syntax
The strings.Index function has this syntax:
strings.Index(s, substr string) int
Here, s is the main string to search in, and substr is the substring you want to find. The function returns the starting index of substr in s, or -1 if substr is not present.
go
package main import ( "fmt" "strings" ) func main() { index := strings.Index("hello world", "world") fmt.Println(index) // Output: 6 }
Output
6
Example
This example shows how to find the index of a substring in a string. It prints the index if found, or a message if not found.
go
package main import ( "fmt" "strings" ) func main() { text := "Go programming language" substring := "program" pos := strings.Index(text, substring) if pos != -1 { fmt.Printf("Substring '%s' found at index %d\n", substring, pos) } else { fmt.Printf("Substring '%s' not found\n", substring) } }
Output
Substring 'program' found at index 3
Common Pitfalls
One common mistake is not checking if the returned index is -1, which means the substring was not found. Using the index without this check can cause errors if you try to slice the string at that position.
Also, strings.Index is case-sensitive, so searching for "Go" and "go" will give different results.
go
package main import ( "fmt" "strings" ) func main() { text := "Hello World" substring := "world" pos := strings.Index(text, substring) // Wrong: Using pos without checking // fmt.Println(text[pos:pos+len(substring)]) // This will panic if pos == -1 // Right: Check if substring exists first if pos != -1 { fmt.Println(text[pos : pos+len(substring)]) } else { fmt.Println("Substring not found") } }
Output
Substring not found
Quick Reference
| Function | Description | Return Value |
|---|---|---|
| strings.Index(s, substr) | Finds first index of substr in s | Index (int) or -1 if not found |
| strings.LastIndex(s, substr) | Finds last index of substr in s | Index (int) or -1 if not found |
| strings.Contains(s, substr) | Checks if substr is in s | Boolean (true/false) |
Key Takeaways
Use strings.Index to find the first position of a substring in a string.
Always check if the returned index is -1 before using it.
strings.Index is case-sensitive; consider strings.ToLower for case-insensitive search.
If you need the last occurrence, use strings.LastIndex instead.
Use strings.Contains if you only need to check presence without the index.