Go by Example: Contains Substring
Checking if a string exists inside another is done with `strings.Contains`. For prefixes and suffixes, use `HasPrefix` and `HasSuffix`.
Code
package main
import (
"fmt"
"strings"
)
func main() {
s := "seafood"
// 1. Contains (Substring check)
// Checks if "foo" is anywhere inside "seafood".
if strings.Contains(s, "foo") {
fmt.Println("Found 'foo'")
}
// 2. HasPrefix (Starts with)
// More efficient than Contains for checking the start.
if strings.HasPrefix(s, "sea") {
fmt.Println("Starts with 'sea'")
}
// 3. HasSuffix (Ends with)
// Checks the end of the string.
if strings.HasSuffix(s, "food") {
fmt.Println("Ends with 'food'")
}
// 4. ContainsAny (Character check)
// Checks if ANY of the characters "x", "y", or "z" are in s.
if !strings.ContainsAny(s, "xyz") {
fmt.Println("No x, y, or z found")
}
}
Explanation
The strings.Contains function is the standard way to check for the presence of a substring. It performs a highly optimized search and returns a boolean. While simple, it is case-sensitive, so "Foo" will not be found in "seafood". For case-insensitive checks, you would typically use strings.Contains(strings.ToLower(s), "foo") or regular expressions.
When validating data formats, checking the beginning or end of a string is common. strings.HasPrefix and strings.HasSuffix are specialized functions for this. They are more readable and performant than using Contains or slicing strings manually. Additionally, strings.ContainsAny is useful for validating that a string does not contain forbidden characters, as it checks for the presence of any character from a provided set.
- Contains: General purpose substring check.
- HasPrefix/Suffix: Optimized for start/end checks.
- ContainsAny: Checks for presence of specific characters.

