Go Reference ยท strings and strconv
Go strings.Index() function
Reference for Go strings.Index, LastIndex, IndexByte, IndexRune, IndexAny and IndexFunc: find byte positions of substrings, and avoid the -1 and byte-offset pitfalls.
strings.Index(s, substr) returns the byte offset of the first occurrence of substr in s, or -1 if it is not there. LastIndex returns the offset of the last occurrence instead.
Variants search for a single byte (IndexByte), a rune (IndexRune), any character from a set (IndexAny) or the first rune matching a predicate (IndexFunc). Each has a Last... counterpart.
i := strings.Index("chicken", "ken") // 4
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func Index(s, substr string) int func LastIndex(s, substr string) int func IndexByte(s string, c byte) int func IndexRune(s string, r rune) int func IndexAny(s, chars string) int func IndexFunc(s string, f func(rune) bool) int
| Name | Description |
|---|---|
s |
The string to search. |
substr |
The substring to find. |
c |
A single byte. Only meaningful for ASCII or when you really mean a byte. |
r |
A rune (Unicode code point). |
chars |
A set of characters; the result is the first position of any of them. |
f |
Predicate on runes. |
Returns: the zero-based byte index of the match, or -1 if there is none.
Edge cases: Index(s, "") is 0; LastIndex(s, "") is len(s). IndexRune with an invalid rune such as utf8.RuneError searches for an invalid encoding. Nothing panics.
Usage notes
- Always check for
-1before using the result as a slice index;s[-1:]panics. - Offsets are bytes, not characters. In the second example
"aรฑb=1"has 5 runes but 6 bytes, andbis at byte 3. The offset is still valid for slicing the same string, which is what you usually want. - Finding all matches: loop with a moving start offset (as above), or use
strings.SplitSeq, or a regexp for patterns. - Just yes or no?
strings.Contains()states the intent better. - Splitting around the first match: prefer
strings.Cut()instead ofIndexand two slices; it is shorter and cannot go out of range. IndexAnyvsIndex:IndexAnytreats its second argument as a set of alternatives, not a sequence.- Performance:
IndexByteis the fastest, using SIMD instructions; use it for single ASCII characters. - Case-insensitive: there is no built-in; lowercase both strings first, remembering that offsets can differ if lowercasing changes byte lengths of some characters.