Go – Check if String contains a Substring

To check if string contains a substring in Go, call Contains function of strings package and provide the string and substring as arguments to the function.

Contains function returns a boolean value. It returns true if the substring is present in the string, or false if not.

The definition of Contains function in strings package is

func Contains(s, substr string) bool

The syntax to check if string substr is present in the string str is

strings.Contains(str, substr)

Examples

In the following example, we check if string substr is present in the string str using Contains function.

example.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "abcdefgh"
	substr := "cd"
	if strings.Contains(str, substr) {
		fmt.Println("The substring is present in the string.")
	} else {
		fmt.Println("The substring is not present in the string.")
	}
}

Output

The substring is present in the string.

Now, let us take values in str and substr such that substr is not present in str, and check this programmatically using Contains function.

example.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "abcdefgh"
	substr := "xy"
	if strings.Contains(str, substr) {
		fmt.Println("The substring is present in the string.")
	} else {
		fmt.Println("The substring is not present in the string.")
	}
}

Output

The substring is not present in the string.

Conclusion

In this Golang Tutorial, we learned how to check if a substring is present in a string in Go programming language, with the help of example programs.