How to check if string contains a substring in Go

Created
Modified

Using strings.Contains Function

How do I check if a string is a substring of another string in Go? Use the function Contains from the strings package.

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

s := "Apple's new iPad Air is $30 off"

// func Contains(s, substr string) bool

res := strings.Contains(s, "iPad") // res = true
res := strings.Contains(s, "ipad") // res = fasle

// case-insensitive
res := strings.Contains(strings.ToLower(s), strings.ToLower("ipad")) // res = true

Using strings.Index Function

Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.

strings.Contains internally calls strings.Index.

s := "Apple's new iPad Air is $30 off"

// func Index(s, substr string) int

i := strings.Index(s, "iPad") // i = 12
i := strings.Index(s, "ipad") // i = -1

// case-insensitive
i := strings.Index(strings.ToLower(s), strings.ToLower("ipad")) // i = 12

Using strings.Split Function

Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators.

s := "Apple's new iPad Air is $30 off"

// func Split(s, sep string) []string

ss := strings.Split(s, "iPad") // len(ss) >= 2

Using strings.Count Function

Count counts the number of non-overlapping instances of substr in s. If substr is an empty string, Count returns 1 + the number of Unicode code points in s.

s := "Apple's new iPad Air is $30 off"

// func Count(s, substr string) int

i := strings.Count(s, "iPad") // i = 1
i := strings.Count(s, "ipad") // i = 0

Using regexp.MatchString Function

MatchString reports whether the string s contains any match of the regular expression pattern.

s := "Apple's new iPad Air is $30 off"

// func MatchString(pattern string, s string) (matched bool, err error)

matched, _ := regexp.MatchString("iPad", s) // matched = true
matched, _ := regexp.MatchString("ipad", s) // matched = false

// case-insensitive
matched, _ := regexp.MatchString("(?i)ipad", s) // matched = true

// regexp.MustCompile
b := regexp.MustCompile("(?i)ipad").MatchString(s) // b = true

Related Tags