The Contains
function tells us whether a substring appears inside a string or not.
To use this function, you must import the strings
package in your file and access the Contains
function within it using the .
notation like so: string.Contains
.
Here, Contains
is the actual function, while string
is the Go package that stores the definition of this function.
func Contains(str, substr string) bool
The Contains
function takes two arguments:
str
: This argument is of the string type and represents the text you want to search in.
substr
: This argument is also of string type and represents the part of the text that you want to search inside the other string.
The Contains
function returns true
if it is able to find the string substr
inside str
, otherwise false
is returned.
Below is a simple example where we use the Contains
function to check if “ee” is present inside a string.
package mainimport ("fmt""strings")func main() {str := "Beep Beep"substr := "ee"check:= strings.Contains(str,substr)if check{fmt.Print("We found \"",substr,"\" in \"",str,"\"")} else{fmt.Print("\"", substr,"\" is not in \"",str,"\"")}}
Now, this is an example where the Contains
function fails to find the substring.
package mainimport ("fmt""strings")func main() {str := "Hola Amigos!!"substr := "ee"check:= strings.Contains(str,substr)if check{fmt.Print("We found \"",substr,"\" in \"",str,"\"")} else{fmt.Print("\"", substr,"\" is not in \"",str,"\"")}}