How to Check If a String Contains a Substring in Go

Use the `strings.Contains()` function from the standard library, which returns a boolean indicating whether the substring exists within the target string.

Use the strings.Contains() function from the standard library, which returns a boolean indicating whether the substring exists within the target string. It is the most efficient and idiomatic way to perform this check, handling empty strings and nil cases correctly without needing manual loops or regex.

Here is a basic usage example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	text := "The quick brown fox jumps over the lazy dog"
	sub := "fox"

	if strings.Contains(text, sub) {
		fmt.Printf("'%s' is found in the text.\n", sub)
	} else {
		fmt.Printf("'%s' is not found.\n", sub)
	}
}

If you need case-insensitive matching, convert both strings to lowercase before checking, or use strings.ContainsFold() for more complex Unicode case folding. For example:

import (
	"fmt"
	"strings"
)

func main() {
	text := "Go is awesome"
	sub := "go"

	// Case-insensitive check
	if strings.ContainsFold(text, sub) {
		fmt.Println("Match found (case-insensitive)")
	}
}

Avoid using regular expressions (regexp) for simple substring checks, as they add unnecessary overhead and complexity. strings.Contains() is optimized in the standard library and runs in O(n) time, making it suitable for high-performance scenarios.

Note that strings.Contains() treats the input as a UTF-8 string and works correctly with multi-byte characters. If you're dealing with runes (Unicode code points) and need to check for a specific rune, use strings.ContainsRune() instead:

if strings.ContainsRune("hello", 'e') {
	fmt.Println("Contains 'e'")
}

In summary, always prefer strings.Contains() for substring checks unless you have a specific need for case folding, rune-level checks, or pattern matching.