Go – Get Index of Substring in String
To get the index of a substring in a Go string, call the strings.Index() function with the source string and the substring to search for. The function returns the byte index of the substring’s first occurrence, or -1 when no match is found.
Syntax of strings.Index() in Go
The syntax to get the index of the first occurrence of substring substr in a string str using strings.Index() is
strings.Index(str, substr)
where
stringsis the package.Indexis the function name.stris the string in which we have to find the index ofsubstr.
strings.Index() returns an int. The returned value is the zero-based byte position at which the first matching substring begins.
Find the First Index of a Substring in a Go String
In the following program, we will take a string Welcome to Go Tutorial, Go Examples and find the index of first occurrence of substring Go.
example.go
package main
import (
"fmt"
"strings"
)
func main() {
var str = "Welcome to Go Tutorial, Go Examples"
var substr = "Go"
var index = strings.Index(str, substr)
fmt.Println("The index of substring in this string is: ", index)
}
Output
The index of substring in this string is: 11
The first character in a string has index 0. In this example, the first occurrence of Go begins at byte index 11. The later occurrence is ignored because strings.Index() returns only the first match.
When the Substring Is Not Present
If the substring is not present in the input string, strings.Index() returns -1.
In the following program, we will take a string and substring such that substring is not present in the string. We will then use Index() to find the index of substring in given string. Since substring is not present in the string, Index() should return -1.
example.go
package main
import (
"fmt"
"strings"
)
func main() {
var str = "Welcome to Go Tutorial, Go Examples"
var substr = "Python"
var index = strings.Index(str, substr)
fmt.Println("The index of substring in this string is: ", index)
}
Output
The index of substring in this string is: -1
Check for -1 before using the returned index to slice the string. Attempting to slice a string with a negative index causes a runtime panic.
Check the Index Before Extracting the Substring
The following example searches for a substring and extracts the text beginning at the match only when the substring exists.
package main
import (
"fmt"
"strings"
)
func main() {
text := "Learn Go string functions"
search := "Go"
index := strings.Index(text, search)
if index == -1 {
fmt.Println("Substring not found")
return
}
fmt.Println("Index:", index)
fmt.Println("String from match:", text[index:])
}
Output
Index: 6
String from match: Go string functions
Find a Substring Starting After a Specific Index
strings.Index() does not accept a starting-index argument. To begin searching from a particular byte position, slice the string at that position, search the sliced value, and then add the starting position to the result.
package main
import (
"fmt"
"strings"
)
func main() {
text := "Go basics, Go strings, Go examples"
search := "Go"
start := 3
relativeIndex := strings.Index(text[start:], search)
if relativeIndex == -1 {
fmt.Println("Substring not found")
return
}
absoluteIndex := start + relativeIndex
fmt.Println("Index after the starting position:", absoluteIndex)
}
Output
Index after the starting position: 11
The index returned from strings.Index(text[start:], search) is relative to the sliced string. Adding start converts it to an index in the original string.
Find Every Occurrence of a Substring in Go
To collect all non-overlapping occurrences, repeatedly search the remaining portion of the string and move the search position past each match.
package main
import (
"fmt"
"strings"
)
func main() {
text := "Go basics, Go strings, Go examples"
search := "Go"
start := 0
for start < len(text) {
relativeIndex := strings.Index(text[start:], search)
if relativeIndex == -1 {
break
}
index := start + relativeIndex
fmt.Println(index)
start = index + len(search)
}
}
Output
0
11
23
This loop finds non-overlapping matches. When overlapping matches are required, advance by one byte or one decoded rune instead of advancing by len(search).
Byte Indexes and Unicode Characters in Go Strings
A Go string is a read-only sequence of bytes, usually containing UTF-8 text. Therefore, strings.Index() returns a byte index rather than a character or rune position. For ASCII text, byte indexes and character positions are the same. They can differ when the text before the match contains multibyte Unicode characters.
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func main() {
text := "नमस्ते Go"
search := "Go"
byteIndex := strings.Index(text, search)
runeIndex := utf8.RuneCountInString(text[:byteIndex])
fmt.Println("Byte index:", byteIndex)
fmt.Println("Rune index:", runeIndex)
}
Output
Byte index: 19
Rune index: 7
The byte index is suitable for slicing the original string because Go string slicing also uses byte indexes. Use rune counting only when the application needs a human-readable Unicode character position.
Related Go String Search Functions
strings.LastIndex(s, substr)returns the byte index of the last occurrence of a substring.strings.Contains(s, substr)reports whether a substring is present without returning its position.strings.IndexByte(s, b)searches for a single byte.strings.IndexRune(s, r)searches for the first occurrence of a Unicode code point.strings.IndexAny(s, chars)returns the index of the first UTF-8 character found from a set of characters.
Use strings.Index() when the search value is a string and the position of its first occurrence is needed.
Edge Cases for strings.Index()
- The search is case-sensitive. Searching for
godoes not matchGo. - An empty substring returns
0because an empty string is considered to occur at the beginning of every string. - If the substring is longer than the source string, the result is
-1. - Only the first occurrence is returned, even when the substring appears multiple times.
- The result is a byte index and can be used directly with Go string slicing.
Frequently Asked Questions About Substring Indexes in Go
Can you index a string in Go?
Yes. An expression such as s[i] accesses the byte at index i, not necessarily a complete Unicode character. To iterate over decoded Unicode code points, use a range loop over the string.
How do I check whether a Go string contains a substring?
Use strings.Contains(s, substr) when only a Boolean result is required. Use strings.Index(s, substr) when the location of the match is also needed.
How do I find the last index of a substring in Go?
Use strings.LastIndex(s, substr). It returns the byte index of the final occurrence or -1 when the substring is absent.
Is strings.Index() case-sensitive?
Yes. For a simple case-insensitive search, both values can be normalized with strings.ToLower() before searching. Be aware that full Unicode case handling can require more careful normalization depending on the application.
Why does strings.Index() return a byte position?
Go strings are byte sequences, and UTF-8 characters can occupy more than one byte. Returning a byte index makes the result compatible with string slicing operations such as s[index:].
Editorial QA Checklist for Go Substring Index Examples
- Confirm that every example imports the
stringspackage when callingstrings.Index(). - Verify that stated indexes are zero-based byte positions, especially in Unicode examples.
- Check that code handles the
-1result before slicing a string. - Confirm that searches from a chosen starting position add the slice offset back to the relative result.
- Verify that examples distinguish first-match searches from last-match and all-match searches.
Summary of Finding a Substring Index in Go
In this Go Tutorial, we learned how to find the first index of a substring using strings.Index(). The function returns a zero-based byte index when the substring is present and -1 otherwise. We also covered searching after a specified position, finding multiple occurrences, safely extracting text from a match, and interpreting indexes in strings containing Unicode characters.
TutorialKart.com