Go Reference ยท strings and strconv
Go strings.Contains() function
Reference for Go strings.Contains, ContainsAny, ContainsRune and ContainsFunc: test whether a string holds a substring, any of several characters or a rune.
strings.Contains(s, substr) reports whether substr appears anywhere inside s. It is case-sensitive and works on bytes, which is correct for UTF-8 because a valid substring always matches at character boundaries.
Three siblings cover related questions: ContainsAny (is any character from a set present), ContainsRune (is this one rune present) and ContainsFunc (does any rune satisfy a predicate).
ok := strings.Contains("seafood", "foo") // true
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 Contains(s, substr string) bool func ContainsAny(s, chars string) bool func ContainsRune(s string, r rune) bool func ContainsFunc(s string, f func(rune) bool) bool
| Name | Description |
|---|---|
s |
The string to search in. |
substr |
The substring to look for. An empty substr is always found. |
chars |
A set of characters; true if s contains at least one of them. |
r |
A single rune to look for. |
f |
Predicate called for each rune of s; searching stops at the first true. |
Returns: a bool. These functions never return an error and never panic.
Edge cases: Contains(s, "") is true for every s, including the empty string. ContainsAny(s, "") is false. ContainsFunc was added in Go 1.21.
Usage notes
- Case-sensitive. For case-insensitive tests lowercase both sides (see the second example) or use
strings.EqualFoldwhen you need equality rather than containment. Lowercasing allocates new strings, so for hot paths consider a regular expression with(?i). ContainsAnytakes a set, not a sequence.ContainsAny("go", "og")istruebecause each character is checked on its own. UseContainsto test for the exact sequence.- Need the position? Use
strings.Index():Contains(s, x)is the same asIndex(s, x) >= 0. - Slices of strings. To check if a slice contains a string use
slices.Contains, not this function. - Bytes.
bytes.Containsis the[]byteversion. - Performance. Single-byte patterns use optimized assembly; longer ones use fast algorithms. Searching is O(n) in the typical case, so avoid calling it in a nested loop over big inputs.
- Unicode normalization.
"รฉ"written as one code point does not match"e"plus a combining accent; normalize withgolang.org/x/text/unicode/normif that matters.